HMAC-SHA1:如何在Java中正确执行它?
我散列使用HMAC-SHA1一些值,在Java中使用下面的代码: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中有类似的功能,我用来比较的返回值通过我的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函数返回的值,我找不到原因。
任何提示?
在您的PHP端,围绕该键使用单引号,以便$
字符不被视为变量引用。即,
hash_hmac("sha1", "helloworld", 'PRIE7$oG2uS-Yf17kEnUEpi5hvW/#AFo')
否则,你真的拿到钥匙是PRIE7-Yf17kEnUEpi5hvW/#AFo
(假设变量$oG2uS
没有定义)。
真棒测距仪! – 2011-06-10 22:55:10
双引号(“”)中的任何$符号都被认为是PHP中的一个变量。您可以使用单引号避免错误通过前一个评论者指出的,或者你可以摆脱美元符号如下
hash_hmac("sha1", "helloworld", "PRIE7\$oG2uS-Yf17kEnUEpi5hvW/#AFo")
通知$现在是\ $
在的Java,并使用行家:
添加下面的依赖到pom.xml
:
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4</version>
</dependency>
,然后尝试使用此
HmacUtils.hmacSha1Hex(key, string_to_sign);
签署它不会将PHP中的$ chars解释为变量吗? – 2011-06-10 22:16:40
为什么你需要十六进制相位? – 2014-06-10 06:51:14