59

我正在使用 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 函数返回的值,我不知道为什么。

有小费吗?

4

5 回答 5

52

在您的 PHP 端,在键周围使用单引号,这样该$字符就不会被视为变量引用。IE,

hash_hmac("sha1", "helloworld", 'PRIE7$oG2uS-Yf17kEnUEpi5hvW/#AFo')

否则,您真正得到的关键是(假设未定义PRIE7-Yf17kEnUEpi5hvW/#AFo变量)。$oG2uS

于 2011-06-10T22:21:31.197 回答
20

推荐Apache Common Codec Library,相当简单易用。 HmacUtils.hmacSha1Hex(key, string_to_sign);

于 2016-01-13T06:21:41.347 回答
7

双引号 ("") 中的任何 $ 符号都被视为 PHP 中的变量。您可以通过使用前面评论者指出的单引号来避免错误,或者您可以转义美元符号,如下所示

hash_hmac("sha1", "helloworld", "PRIE7\$oG2uS-Yf17kEnUEpi5hvW/#AFo")

注意 $ 现在是 \$

于 2013-04-27T16:17:32.450 回答
7

从 Apache commons 中指出 HmacUtils 的其他答案现在已被弃用。Apache commons 现在建议使用:

new HmacUtils(HmacAlgorithms.HMAC_SHA_1, key).hmacHex(string_to_sign)

于 2019-03-01T21:13:36.443 回答
2

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>

然后尝试使用此签名

HmacUtils.hmacSha1Hex(key, string_to_sign);
于 2017-10-30T15:38:08.683 回答