HMAC-SHA1:如何在 Java 中正确执行? [英] HMAC-SHA1: How to do it properly in Java?

查看:21
本文介绍了HMAC-SHA1:如何在 Java 中正确执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 HMAC-SHA1 散列一些值,在 Java 中使用以下代码:

I'm hashing some values using HMAC-SHA1, using the following code in 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 实现返回的值.

In PHP there's a similar function hash_hmac(algorithm, data, key) that I use to compare the values returned by my Java implementation.

所以第一次尝试是:

hash_hmac("sha1", "helloworld", "mykey") // PHP

返回:74ae5a4a3d9996d5918defc2c3d475471bbf59ac

我的 Java 函数也返回 74ae5a4a3d9996d5918defc2c3d475471bbf59ac.

My Java function returns 74ae5a4a3d9996d5918defc2c3d475471bbf59ac as well.

好的,它似乎工作.然后我尝试使用更复杂的密钥:

Ok, it seems working. Then I try to use a more complex key:

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

返回:e98bcc5c5be6f11dc582ae55f520d1ec4ae29f7a

虽然这次我的 Java impl 返回:c19fccf57c613f1868dd22d586f9571cf6412cd0

While this time my Java impl returns: c19fccf57c613f1868dd22d586f9571cf6412cd0

我的 PHP 代码返回的哈希值与我的 Java 函数返回的值不相等,我找不到原因.

The hash returned by my PHP code is not equal to the value returned by my Java function, and I can't find out why.

有什么建议吗?

推荐答案

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

On your PHP side, use single-quotes around the key so that the $ character is not treated as a variable reference. i.e.,

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

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

Otherwise, the key you really get is PRIE7-Yf17kEnUEpi5hvW/#AFo (assuming the variable $oG2uS is not defined).

这篇关于HMAC-SHA1:如何在 Java 中正确执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆