【问题标题】:php and java hmac_sha1 hashing are not the samephp 和 java hmac_sha1 哈希不一样
【发布时间】:2012-08-19 07:47:16
【问题描述】:

我正在尝试将一条消息散列到用 php 编写并由 HMAC_SHA1 算法编码的服务器端(我无法更改他的代码)。我正在用 Java 编写代码。 php代码如下:

$utf8Str = mb_convert_encoding($strToSign, "UTF-8");
$hmac_sha1_str = base64_encode(hash_hmac("sha1", $utf8Str, KEY));
$signature = urlencode($hmac_sha1_str);

我的java代码是:

private static String HashStringSign(String toHash){
try {
    String afterUTF = new String(toHash.getBytes(), "UTF-8");
    String res = hmac_sha1(afterUTF, SecretAccessKey);
    String signature = new String(Base64.encode(res.getBytes()));
    String result = URLEncoder.encode(signature);
        return result;
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

private static String hmac_sha1(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);
        return new String(hexBytes, "UTF-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

我遵循了 php 代码中使用的每种哈希方法,并且按照您所看到的相同顺序。也许 java 中有一个函数在 php 中的工作方式不同?

我正在使用 - com.sun.org.apache.xml.internal.security.utils.Base64 java.net.URLEncoder、javax.crypto 和 org.apache.commons.codec.binary

谢谢!

【问题讨论】:

    标签: java php base64 hashcode hmacsha1


    【解决方案1】:

    在您的hash_hmac 函数中,您需要将第四个参数设置为true。

    PHP 代码不负责,仅限 Java:

    所以现在你说你不能改变 PHP 端,你可以对你的 Java 代码做如下操作。

    在 Java 代码的最后一步中,您将原始字节数组转换为十六进制。但是,PHP 会生成一个 base64 编码的十六进制,而不仅仅是十六进制。

    因此,在您的 Java 步骤结束时,只需对您的十六进制进行 base64 编码,您将获得相同的值。 https://stackoverflow.com/questions/9845767/base64-encoder-java#

    【讨论】:

    • 感谢您的回复!但是,正如我之前提到的,我不对 php 代码负责,也不能更改它。是否可以修改java代码中的某些内容?
    猜你喜欢
    • 1970-01-01
    • 2020-10-28
    • 2021-12-23
    • 2014-05-19
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多