Calculate HMAC-SHA256 digestion in ColdFusion using Java

We are trying to calculate the HMAC-SHA256 digest in ColdFusion, and we use the HMAC CFC, but in one case it produces a different result for the digest compared to the data generated in different languages ​​- I tried the same data using Ruby and PHP and get Expected Result. I also tried my own tag CF_HMAC, on which it is based, and get the same results.

I understand that of CF8 encrypt(), HMAC-SHA256 is supported, but it is available only in Enterprise (which we don’t have) and is not even available in the developer version for testing.

So my question is: can I do this by accessing Java from CF?

+5
source share
2 answers

Here is what I did:

secret = createObject('java', 'javax.crypto.spec.SecretKeySpec' ).Init(my_key.GetBytes(), 'HmacSHA256');
mac = createObject('java', "javax.crypto.Mac");
mac = mac.getInstance("HmacSHA256");
mac.init(secret);
digest = mac.doFinal(my_data.GetBytes());

This gives you an array of bytes, which can then be converted to a string.

+11
source

Here is an example of a DEfusion answer with various I / O formats. My key is hex, my data is below ascii (so UTF-8 will do it), and I need base64 output, so I pass the appropriate arguments to the BinaryDecode and CharsetDecode format:

<cfset keybytes = BinaryDecode(SECRET_KEY, "Hex")>
<cfset databytes = CharsetDecode(data, "UTF-8")>
<cfset secret = createObject("java", "javax.crypto.spec.SecretKeySpec").Init(keybytes,"HmacSHA256")>
<cfset mac = createObject("java", "javax.crypto.Mac")>
<cfset mac = mac.getInstance("HmacSHA256")>
<cfset mac.init(secret)>
<cfset digest = mac.doFinal(databytes)>
<cfset result = BinaryEncode(digest, "Base64")>
0
source

All Articles