HMAC-SHA1:如何在Java中正确执行?
我正在使用HMAC-SHA1对一些值进行散列,使用Java中的以下代码:HMAC-SHA1:如何在Java中正确执行?,java,hash,sha1,hmac,Java,Hash,Sha1,Hmac,我正在使用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 = ne
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\u hmac(算法、数据、键)
,我用它来比较Java实现返回的值
因此,第一次尝试是:
hash_hmac("sha1", "helloworld", "mykey") // PHP
返回:74AE5A4A3D9996D5918DEFC2C3D47571BBF59AC
我的Java函数也返回74ae5a4a3d9996d5918defc2c3d475471bbf59ac
好的,它似乎起作用了。然后我尝试使用更复杂的键:
hash_hmac("sha1", "helloworld", "PRIE7$oG2uS-Yf17kEnUEpi5hvW/#AFo") // PHP
返回:E98BCC5BE6F11DC582AE55F520D1EC4AE29F7A
而这次我的Java impl返回:c19fccf57c613f1868dd22d586f9571cf6412cd0
PHP代码返回的哈希值与Java函数返回的值不相等,我也不知道为什么
任何提示?在PHP端,在键周围使用单引号,以便
$
字符不被视为变量引用。i、 e
hash_hmac("sha1", "helloworld", 'PRIE7$oG2uS-Yf17kEnUEpi5hvW/#AFo')
否则,您真正得到的关键是
PRIE7-Yf17kEnUEpi5hvW/#AFo
(假设变量$oG2uS
未定义)。双引号(“”)中的任何$符号在PHP中都被视为变量。您可以通过使用前面的评论员指出的单引号来避免错误,或者您可以如下转义美元符号
hash_hmac("sha1", "helloworld", "PRIE7\$oG2uS-Yf17kEnUEpi5hvW/#AFo")
请注意,$现在是\$推荐的,非常简单且易于使用。
HmacUtils.hmacSha1Hex(键,字符串到符号)在Java中编码>,并使用maven:
将以下依赖项添加到pom.xml
:
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4</version>
</dependency>
其他指出ApacheCommons中的HMacutil的答案到目前为止已经被弃用。Apache commons现在建议使用:
新的HmacUtils(HmacAlgorithms.HMAC_SHA_1,key)。hmacHex(string_to_sign)
它不会将PHP中的$chars解释为变量吗?为什么需要十六进制阶段?我有类似的问题,无法解决它。现在改用这个:新的HmacUtils(HmacAlgorithms.HMAC_SHA_1,key).hmacHex(inputStreamOfContent);hmacSha1Hex已弃用,请更新您的答案
HmacUtils.hmacSha1Hex(key, string_to_sign);