I am trying to mimic the pseudocode as below in Java, but get a different result. Could anyone please advise what I have done wrong here? Very appreciated.
Pseudo code is telling me the resulting hash should be:
69H45OZkKcmR9LOszbajUUPGkGT8IqasGPAWqW/1stGC2Mex2qhIB6aDbuoy7eGfMsaZiU8Y0lO3mQxlsWNPrw==
whereas my code is giving:
2pIphF0hOqzHqMlGk8KRYGi+/3OPYg+CF9X+qRdGeUP+zHxXYFzdbX/W+8/LFkUt8Pn1M4lXnwg0pSjDz51F+Q==
Pseudo Code:
function hmac_512(msg, sec) {
sec = Base64Decode(sec);
result = hmac(msg, sec, sha512);
return Base64Encode(result);
}
secret = "7pgj8Dm6";
message = "Test\0Message";
result = hmac_512(message, secret);
if (result == "69H45OZkKcmR9LOszbajUUPGkGT8IqasGPAWqW/1stGC2Mex2qhIB6aDbuoy7eGfMsaZiU8Y0lO3mQxlsWNPrw==")
print("Success!");
else
printf("Error: %s", result);
Java / Groovy
String sign(String base64Key, byte[] bytes) {
Mac mac = Mac.getInstance("HmacSHA512");
SecretKey secretKey = new SecretKeySpec(Base64.decode(base64Key.getBytes()), "HmacSHA512");
mac.init(secretKey);
mac.update(bytes);
return Base64.encodeBytes(mac.doFinal()).trim();
}
def tonce = (new Date()).time*1000
def postBody['tonce'] = tonce;
// put other parameters in postBody
String postBodyInJson = new Gson().toJson(postBody)
String path = 'api/3/receive'
String data = path + "\0" + postBodyInJson
String sign = sign(secret, data.getBytes())
My Code:
private static String CreateToken(String message, String secretKey)
{
message = "Test\\oMessage";
secretKey = "7pgj8Dm6";
String hash = "";
try {
Mac sha512_HMAC = Mac.getInstance("HmacSHA512");
SecretKeySpec secret_key = new SecretKeySpec(Base64.decodeBase64(secretKey), "HmacSHA512");
sha512_HMAC.init(secret_key);
sha512_HMAC.update(message.getBytes());
hash = Base64.encodeBase64String(sha512_HMAC.doFinal()).trim();
System.out.println(hash);
}
catch (Exception e){
System.out.println("Error");
}
return hash;
}