Calculate HMAC-SHA256 digest in ColdFusion using Java

耗尽温柔 提交于 2019-12-19 07:32:14

问题


We are trying to calculate a HMAC-SHA256 digest in ColdFusion and we are using the HMAC CFC, but in one case it is producing a different result for the digest compared to ones generated in different languages - have tried the same data using Ruby & PHP and get the expected result. I have also tried the CF_HMAC custom tag it is based on and get the same results.

I understand that from CF8 encrypt() supports HMAC-SHA256, but it's only available in Enterprise (which we don't have) and isn't even available in developer version for me to test.

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


回答1:


This is what I ended up doing:

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 the byte array, which you can then convert to a string.




回答2:


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

<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")>


来源:https://stackoverflow.com/questions/951477/calculate-hmac-sha256-digest-in-coldfusion-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!