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

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

我正在尝试在 java (android) 中设置安全散列密钥。它没有得到与 php 方面相同的结果(我将其用作参考并且有效)。

我遇到过很多类似的问题,但是(只有一个,我试过了但是不行)none没有解决清楚。这是我测试过的代码。

// 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 的 this Whosebug answer,而不是 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 端相同的十六进制密钥。