我试图在Java中模仿下面的伪代码,但获得了不同的结果。谁能告诉我这里做错了什么?非常感谢。
伪代码告诉我结果哈希应该是:
69H45OZkKcmR9LOszbajUUPGkGT8IqasGPAWqW / 1stGC2Mex2qhIB6aDbuoy7eGfMsaZiU8Y0lO3mQxlsWNPrw ==
而我的代码却给出了:
2pIphF0hOqzHqMlGk8KRYGi + / + 3OPYg + CF9X + qRdGeUP zHxXYFzdbX / W + 8 / LFkUt8Pn1M4lXnwg0pSjDz51F + Q ==
伪代码:
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())
我的代码:
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;
}
答案 0 :(得分:0)
this code run for me
public String getHmacSha512(String postData) {
Mac sha512_HMAC;
String result = "";
try {
byte[] byteKey = Constantes.PUBLIC_KEY.getBytes("UTF-8");
final String HMAC_SHA512 = "HmacSHA512";
sha512_HMAC = Mac.getInstance(HMAC_SHA512);
SecretKeySpec keySpec = new SecretKeySpec(byteKey, HMAC_SHA512);
sha512_HMAC.init(keySpec);
byte[] mac_data = sha512_HMAC.doFinal(postData.getBytes("UTF-8"));
result = bytesToHex(mac_data);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// System.out.println("Done");
}
return result;
}
public String bytesToHex(byte[] bytes) {
final char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}