我正在使用 HMAC-SHA1 散列一些值,使用 Java 中的以下代码:
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
返回:e98bcc5c5be6f11dc582ae55f520d1ec4ae29f7a
虽然这次我的 Java impl 返回:c19fccf57c613f1868dd22d586f9571cf6412cd0
我的 PHP 代码返回的哈希值不等于我的 Java 函数返回的值,我不知道为什么。
有小费吗?