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
hash_hmac(algorithm, data, key)
PHP には、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 関数から返された値と等しくなく、その理由がわかりません。
任意のヒント?