lambypie
lambypie

Reputation: 481

ColdFusion alternative for PHP md5 function

I have tried to HMAC MD5 implementation in Coldfusion. I am having PHP code for the same. I would like find out the best way to convert the same into ColdFusion.

PHP

  $output = hmac($key, $str);

  function hmac ($key, $data)
  {
    // RFC 2104 HMAC implementation for php.
    // Creates an md5 HMAC.
    // Eliminates the need to install mhash to compute a HMAC

    $b = 64; // byte length for md5
    if (strlen($key) > $b) {
      $key = pack("H*",md5($key));
    }
    $key  = str_pad($key, $b, chr(0x00));
    $ipad = str_pad('', $b, chr(0x36));
    $opad = str_pad('', $b, chr(0x5c));
    $k_ipad = $key ^ $ipad ;
    $k_opad = $key ^ $opad;

    return md5($k_opad  . pack("H*",md5($k_ipad . $data)));
  }

I have tried the following in code in ColdFusion.

ColdFusion

  <cfset outputOld = hmacEncrypt(key, input, 'HmacMD5') />
  <cfset output = binaryEncode(outputOld, 'hex') />

  <cffunction name="hmacEncrypt" returntype="binary" access="public" output="false">
    <cfargument name="signKey" type="string" required="true" />
    <cfargument name="signMessage" type="string" required="true" />
    <cfargument name="algorithm" type="string" default="HmacMD5" />
    <cfargument name="charset" type="string" default="UTF-8" />

    <cfset var msgBytes = charsetDecode(arguments.signMessage, arguments.charset) />
    <cfset var keyBytes = charsetDecode(arguments.signKey, arguments.charset) />
    <cfset var keySpec = createObject("java","javax.crypto.spec.SecretKeySpec")  />
    <cfset var mac = createObject("java","javax.crypto.Mac") />

    <cfset key = keySpec.init(keyBytes, arguments.algorithm) />
    <cfset mac = mac.getInstance(arguments.algorithm) />
    <cfset mac.init(key) />
    <cfset mac.update(msgBytes) />

    <cfreturn mac.doFinal() />
  </cffunction>

But I am getting different values for PHP and ColdFusion. I need to get the same as PHP.

Any help is much appreicated.

Upvotes: 1

Views: 413

Answers (1)

Anurag
Anurag

Reputation: 1038

I strongly recommend you use the Crypto.cfc by Bennadel.It provides methods for generating Hmac values with the SHA-1, SHA-256, and MD5 algorithms and is very cleanly written.

Also, I would prefer to use the hash_hmac() function available in PHP for it's performance and simplicity.

string hash_hmac('md5', $input, $secretKey);

As far as I can understand, you're comparing a string output with a binary output, which won't match. md5 returns a string output but the doFinal() in javax.crypto.Mac returns a byte[] representation. You need to typecast accordingly. Correct it and the result is the same.

Update

You can check the base code in both the language:

ColdFusion Code

PHP Code

As you can see, the results are the same. Dude, it's your code only and it's working fine with the addition of only lcase as pointed by @Leigh.

Upvotes: 1

Related Questions