为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
繁华开满天机 2021-06-28 13:43:06
我正在尝试在 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 codeprivate 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 代码?
查看完整描述

1 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

而不是密钥上的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 端相同的十六进制密钥。


查看完整回答
反对 回复 2021-07-09
  • 1 回答
  • 0 关注
  • 294 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信