猿问

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

我正在尝试在 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 相同的输出,即使用pack('H*', $secret)Java 代码?


繁华开满天机
浏览 295回答 1
1回答

拉莫斯之舞

而不是密钥上的string.getBytes java 函数,我使用他的函数来获取字节,&nbsp; &nbsp; public byte[] hexToString(String hex) {&nbsp; &nbsp; &nbsp; &nbsp; // hexToString that works at a byte level, not at character level&nbsp; &nbsp; &nbsp; &nbsp; byte[] output = new byte[(hex.length() + 1) / 2];&nbsp; &nbsp; &nbsp; &nbsp; for (int i = hex.length() - 1; i >= 0; i -= 2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int from = i - 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (from < 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; from = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String str = hex.substring(from, i + 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output[i/2] = (byte)Integer.parseInt(str, 16);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return output;&nbsp; &nbsp; }现在我得到与 php 端相同的十六进制密钥。
随时随地看视频慕课网APP
我要回答