Brad Mash
Brad Mash

Reputation: 69

ColdFusion Equivalent to PHP Unpack and SHA1

Here is my problem. In PHP there are two functions that I am having a hard time replicating in ColdFusion.

1) PHP's unpack function which let's you format the output in a given way. One of the format options is 'H' which stands for "Hex string, high nibble first" - How could I replicate this in ColdFusion?

This is what I have so far...

<cfscript>
function stringToBinary( String stringValue ){
    var base64Value = toBase64( stringValue );
    var binaryValue = toBinary( base64Value );
    return( binaryValue );
}

function stringToHex( String stringValue ){
    var binaryValue = stringToBinary( stringValue );
    var hexValue = binaryEncode( binaryValue, "hex" );
    return( lcase( hexValue ) );
}   
</cfscript>

So I can't figure out to specify high nibble in the implementation above (also, I did not write this coldfusion this is courtesy of Ben Nadel).

Secondly, in PHP there is a SHA1 function for hashing... there is an argument to that function which is a boolean argument for "If the optional raw_output is set to TRUE, then the sha1 digest is instead returned in raw binary format with a length of 20, otherwise the returned value is a 40-character hexadecimal number." So my Coldfusion to mimic this is simply using the Hash() function and specifying it to use "SHA-1" and then converting that to binary... but how would I correctly limit it "to 20" in the same exact way PHP does?

I know this is involved by I have been stumped for quite some time now on these two issues... Any help is very much appreciated.

Upvotes: 1

Views: 367

Answers (1)

Leigh
Leigh

Reputation: 28873

using the Hash() function and specifying it to use "SHA-1" and then converting that to binary... but how would I correctly limit it "to 20"

You do not need to do anything. SHA1 produces 160 bits. The binary result will always be 20 bytes, or 40 characters encoded as hexadecimal (two characters per byte).

  hashString = hash("Something wicked this way comes", "sha1");
  hashBinary = binaryDecode( hashString, "hex");
  writeOutput(" String / len("& len(hashString) &")");
  writeOutput(" Binary / arrayLen("& arrayLen(hashBinary) &")");

'H' which stands for "Hex string, high nibble first" figure out to specify high nibble in the implementation above

Is there a specific reason you believe you must do something special/extra? From what I have read, the typical function used to generate hex in PHP, ie bin2hex, defaults to high nibble first, as does CF. Aside from the fact that CF converts the results to upper case, the results are identical. Can you provide a specific example of where the PHP and CF results differ?

PHP:

echo bin2hex("Green Onions");
// result:  477265656e204f6e696f6e73

CF

writeDump( binaryEncode(charsetDecode("Green Onions", "utf-8"), "hex") );
// result: 477265656E204F6E696F6E73 

Upvotes: 5

Related Questions