2

I'm trying to replicate a function in Coldfusion that returns a string. The function looks like this:

<cffunction name="createKey" access="public" output="false" returntype="string"     hint="Creates a propper ecryption/decryption key from a string.">
<cfargument name="thePassword" type="string" required="yes">
<cfargument name="algorithmType" type="string" required="no" default="MD5">
<cfargument name="binaryEncodeType" type="string" required="no" default="Hex">


<cfset var theKey = Hash(ARGUMENTS.thePassword,ARGUMENTS.algorithmType)>
<cfset theKey = ToBase64(BinaryDecode(theKey, ARGUMENTS.binaryEncodeType))>

<cfreturn theKey>
</cffunction>

The string this returns is a key value, so I must get an identical matching value from the new .Net function.

This .net equivalent for this line works fine:

<cfset var theKey = Hash(ARGUMENTS.thePassword,ARGUMENTS.algorithmType)>

Replicating this, however:

<cfset theKey = ToBase64(BinaryDecode(theKey, ARGUMENTS.binaryEncodeType))>

Is proving to be difficult. I get that it's decoding the hash and converting it to Base64, but the BinaryDecode function in CF takes "Hex" as a decode type. Any ideas how I might do this in .NET and get a string value identical to what I would get in Coldfusion?

Josh
  • 41
  • 2

1 Answers1

1

Update:

On second thought, this is probably a case where it is best not to do an exact translation. If you simply need to calculate the hash of a plain string, then skip the conversion to hex and work directly with the binary. The resulting base64 string will be the same as before, and will match the result from CF.

C#:

string thePlainTextPassword = "some password";
SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider();
byte[] data = Encoding.UTF8.GetBytes(thePlainTextPassword);
byte[] hash = sha256.ComputeHash(data);
string key = Convert.ToBase64String(hash);

CF Code:

 key = createKey(thePlainTextPassword , "SHA-256", "hex");

Result:

5i4SaTF7llThMU3+y3jymzWtTTYtoKnCzNtoCqU11+o=

Though to answer the original question, if you really need a literal translation, you could use something similar to the suggestion in this answer to convert the hex string into a byte array:

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

Then encode the bytes as base64:

 string hex = "E62E1269317B9654E1314DFECB78F29B35AD4D362DA0A9C2CCDB680AA535D7EA";
 string key = Convert.ToBase64String(StringToByteArray(hex));

Result:

5i4SaTF7llThMU3+y3jymzWtTTYtoKnCzNtoCqU11+o= 
Community
  • 1
  • 1
Leigh
  • 28,765
  • 10
  • 55
  • 103