I am trying to convert this code into java but the results are not accurate
private String hmacDigest(String msg, String keyString, String algo) throws Exception {
String digest = null;
SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), algo);
Mac mac = Mac.getInstance(algo);
mac.init(key);
byte[] bytes = mac.doFinal(msg.getBytes("ASCII"));
StringBuffer hash = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
hash.append('0');
}
hash.append(hex);
}
digest = hash.toString();
return digest;
}
and my codfusion try till this point
<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")>
my knowledge is very limited in java so i am not sure if i am doing it right or wrong
You mixed up the string encodings, so the CFML is actually using different input values than the java code. That's why your results don't match
The java method decodes the key as "UTF-8"
(keyString).getBytes("UTF-8")
.. but the CFML is using "hexadecimal"
<cfset keybytes = BinaryDecode(SECRET_KEY, "Hex")>
The java method decodes the message as "ASCII"
msg.getBytes("ASCII")
... but the CFML is using "UTF-8"
CharsetDecode(data, "UTF-8")
The java result is encoded as "hexadecimal", but the CFML is using "base64"
BinaryEncode(digest, "Base64")
\n
is interpreted as line feed in java. It doesn't work the same way in CF. Instead use chr(10)
.
While the errors are easily fixed, the java code isn't even needed. Use the built in HMAC function instead. It produces the same result. The only difference being that CF returns hexadecimal in all upper case, so you must wrap it in LCASE() to get an exact match.
Lcase( HMac( messageString, keyAsString, algorithm, "ASCII") )