I have no experience with C# and was wondering if someone can help converting this C# snippet into ColdFusion.
string inputString = "abccde";
string securityKey = "abcdefghijk...";
// Convert security key into ASCII bytes using utf8 encoding
byte[] securityKeyBytes = UTF8Encoding.ASCII.GetBytes(securityKey);
// Create an HMACSHA1 hashing object that has been seeded with the security key bytes
HMACSHA1 hasher = new HMACSHA1(securityKeyBytes);
// Convert input string into ASCII bytes using utf8 encoding
byte[] inputBytes = UTF8Encoding.ASCII.GetBytes(inputString.ToCharArray());
// Compute the has value
byte[] hash = hasher.ComputeHash(inputBytes);
// Convert back to a base 64 string
string securityToken = Convert.ToBase64String(hash);
return securityToken;
I found this on stackOverFlow and here what I have so far. I'm I going in the right direction? Any insights would be much appreciated!
<cffunction name="CFHMAC" output="false" returntype="string">
<cfargument name="signMsg" type="string" required="true" />
<cfargument name="signKey" type="string" required="true" />
<cfset var key = createObject("java", "javax.crypto.spec.SecretKeySpec").init(signKey.getBytes(), "HmacSHA1") />
<cfset var mac = createObject("java", "javax.crypto.Mac").getInstance("HmacSHA1") />
<cfset mac.init(key) />
<cfreturn toBase64(mac.doFinal(signMsg.getBytes())) />
</cffunction>
<cfset signMsg= "abccde">
<cfset signatureString = "abcdefghijk...">
<cfset result = CFHMAC(signMsg=signMsg, signKey=signatureString) />
<cfdump var="#result#" />
(Expanded from the comments)
CF11 has an HMAC function already built in, so it is possible you may not need that UDF. I would suggest giving it a try. Take note that the C# code uses UTF8Encoding.ASCII:
ASCII characters are limited to the lowest 128 Unicode characters,
from U+0000 to U+007F....
Note that the ASCII encoding has an 8th bit ambiguity that can allow
malicious use, but the UTF-8 encoding removes ambiguity about the 8th
bit. ... It uses replacement fallback to replace each string that it
cannot encode and each byte that it cannot decode with a question mark
("?") character.
Assuming you need to maintain compatibility with some other application, and must keep the same encoding, UTF8Encoding.ASCII should correspond to "US-ASCII" encoding in CF/Java, but do some testing to verify the handling of invalid characters. If you have the flexibility to change the encoding, I would recommend using UTF-8 instead. Keep in mind, the CF function always returns hexadecimal. If you need a base64 string instead, you will have to convert it with binaryEncode() and binaryDecode().
Example:
<!--- Only required when hard coding UTF8 characters into a script --->
<cfprocessingdirective pageEncoding="utf-8">
<cfset message = "Pi π and Sigma Σ.">
<cfset key = "abcdefghijk">
<cfset hexHash = hmac(message, key, "HMACSHA1", "US-ASCII")>
<cfset base64Hash = binaryEncode(binaryDecode(hexHash, "hex"), "base64")>
<cfdump var="#base64Hash#">
Result:
HMACSHA1 = J2AZf+zhrebIA/tK3i5PYb4b/Fo=
Side note, about the CFHMAC UDF: be very careful with encoding when extracting the bytes of a string. As I noted in the comments, it is best avoid using getBytes() because it assumes the default encoding, whatever that may be. That means it may not always return the desired results, and can vary from one jvm to another. Instead, it is better to always supply a charset explicitly ie getBytes("UTF-8") , getBytes("US-ASCII"), etcetera.
Related
I have a string retrieved from the database that can contain a series of codes in either {} or [] brackets as well as plain, user entered text. For example, each of the following would be possible values:
[code]
[code1][code2]
{code}
{code1}{code2}
{code1} Some user entered text. {code2}{code3} Some more user entered text.
Etc. etc.
What I need to do using ColdFusion is extract the codes within the {} and [] brackets so I can retrieve their descriptions from a database. For example:
{code1} Some user entered text. {code2}{code3} Some more user entered text.
Would become a list similar to:
{code1}|{code2}|{code3}
Normally I could just do something like REMatch but unfortunately I'm stuck doing this on a server running ColdFusion version 4.5 (groan) so my options are limited.
I'm thinking maybe I could do some Replaces on the string to convert it into a pipe delimited list that I can then easily process but I'm not sure if there might be a more straight forward approach? I'm not even really sure what a sensible way to process this using a Replace would be.
<cfset myString = "{code1} Some user entered text {code2}{code3} More user entered text" />
<cfset myArray = listToArray(myString, "{[") />
<cfloop index="i" from="1" to="#arrayLen(myArray)#">
<cfset myArray[i] = "{" & listFirst(myArray[i], "}]") & "}" />
</cfloop>
<cfdump var="#myArray#" />
<hr>
<cfset myList = arrayToList(myArray, "|") />
<cfdump var="#myList#" />
TryCF.com Gist:
https://trycf.com/gist/6035ddc5cd3daa81bc0943f1af33323a/lucee5?theme=monokai
I have gone through a number of other related posts on this subject and have been able to replicate them with no problems. However, I cannot get the expected signature result using my own data, no matter what I try to do. I would greatly appreciate any assistance. Here are the API requirements:
Convert the data to sign from an ASCII string to a byte array
Convert your Secret Access Key from a Base64 string to a byte array
Use the byte array created in step 1 as the key for a HMAC-SHA1 signer
Calculate the HMAC-SHA1 hash of the byte array created in step 2. The result will be a byte array
Convert the byte array created in step 3 to a Base64 encoded string
According to the documentation:
Assuming your Secret Access Key is “AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==”
Assuming data to sign is
“http://membersuite.com/contracts/IConciergeAPIService/WhoAmI00000000-0000-0000-0000-00000000000011111111-1111-1111-1111-111111111111"
Signature should be “2zsMYdHb/MJUeTjv5cQl5pBuIqU=”
I have been unable to get that signature, despite trying a variety of methods from the other posts. For example:
<cffunction name="hmacEncrypt" returntype="binary" access="public" output="false">
<cfargument name="base64Key" type="string" required="true" default="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==">
<cfargument name="signMessage" type="string" required="true" default="http://membersuite.com/contracts/IConciergeAPIService/WhoAmI00000000-0000-0000-0000-00000000000011111111-1111-1111-1111-111111111111">
<cfargument name="encoding" type="string" default="UTF-8">
<cfset var messageBytes = JavaCast("string",arguments.signMessage).getBytes(arguments.encoding)>
<cfset var keyBytes = binaryDecode(arguments.base64Key, "base64")>
<cfset var key = createObject("java","javax.crypto.spec.SecretKeySpec")>
<cfset var mac = createObject("java","javax.crypto.Mac")>
<cfset key = key.init(keyBytes,"HmacSHA512")>
<cfset mac = mac.getInstance(key.getAlgorithm())>
<cfset mac.init(key)>
<cfset mac.update(messageBytes)>
<cfreturn mac.doFinal()>
</cffunction>
Dumping the output of that function does not give me any errors, but neither does it match the expected output. Again, I would greatly appreciate any assistance or nudges in the right direction. I think part of my trouble lies in how I am encoding the key and URL string, but I am not sure. Thank you all in advance!
key.init(keyBytes,"HmacSHA512")
Almost. That UDF is hard coded to use "HmacSHA512". Change it to "HmacSHA1", or better yet, make it a function parameter like "encoding".
Example:
<cfset action = "http://membersuite.com/contracts/IConciergeAPIService/WhoAmI">
<cfset associationId = "00000000-0000-0000-0000-000000000000">
<cfset sessionId = "11111111-1111-1111-1111-111111111111">
<cfset stringToSign = action & associationId & sessionId>
<cfset key = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==">
<cfset result = binaryEncode(hmacEncrypt(key, stringToSign, "US-ASCII"), "base64")>
<cfset writeDump(result)>
Result:
2zsMYdHb/MJUeTjv5cQl5pBuIqU=
NB: As of CF10+, HMAC is a now core function:
<cfset resultAsHex = hmac(stringToSign, binaryDecode(key, "base64"), "hmacsha1", "us-ascii")>
<cfset resultAsBase64 = binaryEncode(binaryDecode(resultAsHex, "hex"), "base64")>
<cfset writeDump(resultAsBase64)>
I'm able to get all the values that I want from cfldap.
But when I try to update the user image I don't know how to send the correct value for the binary image attribute.
I tried getting the image variable from the cffile upload
<cffile action="UPLOAD" filefield="file" destination="c:\inetpub\wwwroot\test" nameconflict="OVERWRITE" result="image" />
Also tried using cfimage with a static image -
<cfimage action="read" source="c:\inetpub\wwwroot\test\image.png" name="anotherImage">
Or even with
<cffile action="READBINARY" file="c:\inetpub\wwwroot\test\image.png" variable="BinaryImageContent">
But in any case, when I call
<cfldap action="modify"
DN="#results.dn#"
attributes="thumbnailPhoto=#obj.image#"
modifytype="replace"
server="myserver"
username="mydomain\myuser"
password="mypass">
The #results.dn# is the DN from the user that I get before (Everything ok on that)
I created the #obj.image# to be able to try all types of variables
Also tried these params:
<cfset obj.test1 = BinaryImageContent />
<cfdump var="#imageGetBlob(anotherImage)#" />
<cfdump var="#toString(obj.test1)#" />
By the way, the error that I get its
One or more of the required attributes may be missing or incorrect or
you do not have permissions to execute this operation on the server.
The problem is that I'm using the domain administrator account to update that
(THIS ERROR IS SOLVED - The network guys hadn't given me this permission... now I have it).
Now what I'm using is the following:
<cffile action="UPLOAD" filefield="file" destination="c:\inetpub\wwwroot\test" nameconflict="OVERWRITE" result="imagem" />
<cfset filename = "C:\inetpub\wwwroot\test\#imagem.serverFile#">
<cffile action="readbinary" file="#filename#" variable="img">
<cfset imgStr = BinaryEncode(img, "hex")>
<cfset imgStr2 = REReplace(imgStr, "..", "\\\0", "ALL")>
<cfldap
action="modify"
DN="#results.dn#"
attributes="thumbnailPhoto=#imgStr2#"
modifytype="replace"
server="myserver"
username="mydomain\myuser"
password="mypass"
>
but I get this binary code
Whats strange, is that before I had a binary code like -1-41 and now, nothing similar...
and when I try to show the pic
And this is one correct image....
EDIT: The original code sample below shows how it could work if ColdFusion wouldn't have a bug (or "very unfortunate design decision") in CFLDAP.
CFLDAP encodes the parameter values you pass to it before sending them to the server. This is nice because you don't have to worry about value encoding. But... it is also not helpful because it means you can't send encoded values yourself anymore, since CF invariably encodes them again.
Bottom line: As far as LDAP is concerned, encoding a file into a hex-string is correct, but CFLDAP mangles that string before sending it to the server. Combined with the fact that CFLDAP does not accept raw binary data this means that you can't use it to update binary attributes.
The comments contain a suggestion for a 3rd-party command line tool that can easily substitute CFLDAP for this task.
You need to send an encoded string to the server as the attribute value. The encoding scheme for binary data in LDAP queries has the form of attribute=\01\02\03\ab\af\cd.
Read your image into a byte array, encode that array into a hex string and prefix every encoded byte with a backslash.
<cffile action="readbinary" file="#filename#" variable="img">
<cfset imgStr = BinaryEncode(img, "hex")>
<cfset imgStr = REReplace(imgStr, "..", "\\\0", "ALL")>
<cfldap
action="modify"
DN="#results.dn#"
attributes="thumbnailPhoto=#imgStr#"
modifytype="replace"
server="myserver"
username="mydomain\myuser"
password="mypass"
>
Also don't forget what the documentation has to say about modifyType.
I recently moved my code from CF9 to CF11 and I am having issues when I am trying to use serializeJSON. According to CF docs:
Starting from ColdFusion 11, the data type is preserved during the
code execution time for Query and CFCs.
SerializeJSON considers datatypes defined in the database for
serialization. If the database defines a column as a string, any
number inserted into the column will still be treated as a string by
SerializeJSON.
But I guess this is not the case....
When I am pulling data out of a varchar column in CF9 it comes out like this "docid":"123" which is what I want but in CF11 the same data look like this "docid":123 and is causing an issue with what I am trying to do.
To be more specific, my ids look like this 2001101009460111385185 which is longer than what javascript can accept and they get converted into scientific notation. With the old format I didn't have this issue because my ids were treated as a string which is what I want.
Note: my code is exactly the same on both versions of CF
Anyone had this issue before and HOW did you go around it?
Code Sample
I am calling this function via an AJAX call, this function returns an array with a struct in it. When I dump the return value after I serialize the result I can see a JSON object in my console but the quotes are missing from all the number values. In a test file I created a simple query and then I am serializing the results and everything looks good......
<cffunction name="locationData" returnformat="json" access="remote">
<cfargument name="locationid" required="yes" type="string">
<cfargument name="clientBrandid" required="yes" type="string">
<cfscript>
locationData = new mod_sigweb.components.xamplifierCFCs.location_info();
result = locationData.getLocation(locationid,clientBrandid);
</cfscript>
<cfdump var="#serializeJSON(result[1],'struct')#">
<cfabort>
<cfreturn #result#>
</cffunction>
The unfortunate workaround that I have had to use for this bug is to concatenate a space to the end of the value
<cfloop index="i" from="1" to="#ArrayLen(result)#">
<cfset result[i].docid = result[i].docid & " "/>
</cfloop>
and then the js has to be aware of this (I know, it's bad) and remove that trailing space.
My client has a database table of email bodies that get sent at certain times to customers. The text for the emails contains ColdFusion expressions like Dear #firstName# and so on. These emails are HTML - they also contain all sorts of HTML mark-up. What I'd like to do is read that text from the database into a string and then have ColdFusion Evaluate() that string to resolve the variables. When I do that, Evaluate() throws an exception because it doesn't like the HTML markup in there (I also tried filtering the string through HTMLEditFormat() as an intermediate step for grins but it didn't like the entities in there).
My predecessor solved this problem by writing the email text out to a file and then cfincluding that. It works. It's seems really hacky though. Is there a more elegant way to handle this using something like Evaluate that I'm not seeing?
What other languages often do that seems to work very well is just have some kind of token within your template that can be easily replaced by a regular expression. So you might have a template like:
Dear {{name}}, Thanks for trying {{product_name}}. Etc...
And then you can simply:
<cfset str = ReplaceNoCase(str, "{{name}}", name, "ALL") />
And when you want to get fancier you could just write a method to wrap this:
<cffunction name="fillInTemplate" access="public" returntype="string" output="false">
<cfargument name="map" type="struct" required="true" />
<cfargument name="template" type="string" required="true" />
<cfset var str = arguments.template />
<cfset var k = "" />
<cfloop list="#StructKeyList(arguments.map)#" index="k">
<cfset str = ReplaceNoCase(str, "{{#k#}}", arguments.map[k], "ALL") />
</cfloop>
<cfreturn str />
</cffunction>
And use it like so:
<cfset map = { name : "John", product : "SpecialWidget" } />
<cfset filledInTemplate = fillInTemplate(map, someTemplate) />
Not sure you need rereplace, you could brute force it with a simple replace if you don't have too many fields to merge
How about something like this (not tested)
<cfset var BaseTemplate = "... lots of html with embedded tokens">
<cfloop (on whatever)>
<cfset LoopTemplate = replace(BaseTemplate, "#firstName#", myvarforFirstName, "All">
<cfset LoopTemplate = replace(LoopTemplate, "#lastName#", myvarforLastName, "All">
<cfset LoopTemplate = replace(LoopTemplate, "#address#", myvarforAddress, "All">
</cfloop>
Just treat the html block as a simple string.
CF 7+: You may use regular expression, REReplace()?
CF 9: use Virtual File System
If the variable is in a structure from, something like a form post, then you can use "StructFind". It does exactly as you request. I ran into this issue when processing a form with dynamic inputs.
Ex.
StructFind(FORM, 'WhatYouNeed')