我正在使用Java用HMAC-SHA1算法对一些值进行哈希,使用以下代码:
public static String hmacSha1(String value, String key) {
try {
// Get an hmac_sha1 key from the raw key bytes
byte[] keyBytes = key.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
// Get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
// Compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(value.getBytes());
// Convert raw bytes to Hex
byte[] hexBytes = new Hex().encode(rawHmac);
// Covert array of Hex bytes to a String
return new String(hexBytes, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Hex()
属于 org.apache.commons.codec
在 PHP 中有类似的函数hash_hmac(algorithm, data, key)
,我用它来比较Java实现返回的值。
因此第一次尝试是:
hash_hmac("sha1", "helloworld", "mykey") // PHP
该函数返回:74ae5a4a3d9996d5918defc2c3d475471bbf59ac
我的Java函数也返回74ae5a4a3d9996d5918defc2c3d475471bbf59ac
。
好的,看起来它正常工作。然后我尝试使用一个更复杂的密钥:
hash_hmac("sha1", "helloworld", "PRIE7$oG2uS-Yf17kEnUEpi5hvW/#AFo") // PHP
我的PHP代码返回的哈希值为:e98bcc5c5be6f11dc582ae55f520d1ec4ae29f7a
而这次我的Java实现返回的是:c19fccf57c613f1868dd22d586f9571cf6412cd0
我的PHP代码返回的哈希值与我的Java函数返回的值不相等,我找不到原因。
有什么提示吗?