繁体   English   中英

Java mac sha256散列与使用pack的php hmac sha256不匹配?

[英]Java mac sha256 hashing does not match with php hmac sha256 using pack?

我正在尝试在java(android)中设置安全哈希键。 它没有得到与php端相同的结果(我用它作为参考,它的工作原理)。

我经历了很多类似的问题,但是(只有一个,我尝试过但不起作用)没有一个问题没有解决清楚。 这是我测试过的代码。

// php code
$secureHash = 'ABCD';
$secret = '123AE45F';
echo '<br> using pack--';
echo hash_hmac('sha256', $secureHash, pack('H*', $secret));
echo '<br> without using pack--';
echo hash_hmac('sha256', $secureHash, $secret, false);

结果与包f7a009f2c3e654fa48296917ab6372ecb7aa2a24c43fccb70af743f66b6dba55 结果没有包fc602f0f6faf2072be9c0b995ee3d603f61414c4beb027b678c90946db6903a2

// Java code
private String getHashCode(String message, String secretKey) {
    Mac mac;
    String result = null;

    try {
        byte[] byteKey = secretKey.getBytes(StandardCharsets.UTF_8);

        final String hmacSHA256 = "HmacSHA256";
        mac = Mac.getInstance(hmacSHA256);
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), hmacSHA256);
        sha256HMAC.init(keySpec);

        byte[] mac_data = sha256HMAC.doFinal(message.getBytes(StandardCharsets.UTF_8));
        result = bytesToHex(mac_data);

        System.out.println("getHashCode: result " + result);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }

    return result;
}

在Java代码中,我得到的输出为fc602f0f6faf2072be9c0b995ee3d603f61414c4beb027b678c90946db6903a2

与没有包的PHP代码相同。 我如何实现与PHP相同的输出,即在Java代码中使用pack('H*', $secret)

感谢@rolfl的这个stackoverflow回答 ,而不是秘密密钥上的string.getBytes java函数,我使用他的函数来获取字节,

    public byte[] hexToString(String hex) {
        // hexToString that works at a byte level, not at character level
        byte[] output = new byte[(hex.length() + 1) / 2];
        for (int i = hex.length() - 1; i >= 0; i -= 2) {
            int from = i - 1;
            if (from < 0) {
                from = 0;
            }
            String str = hex.substring(from, i + 1);
            output[i/2] = (byte)Integer.parseInt(str, 16);
        }
        return output;
    }

现在我得到与php类相同的十六进制类型密钥。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM