简体   繁体   中英

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

I'm trying to setup a secure hash key in java (android). It's not getting the same result as that of php side (which I use as a reference and it works).

I've gone through many similar questions, but (only one, I tried it but doesn't work) none doesn't solved it clearly. Here's the codes I've tested.

// 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);

result with pack : f7a009f2c3e654fa48296917ab6372ecb7aa2a24c43fccb70af743f66b6dba55 result without pack : 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;
}

In the Java code I'm getting the output as fc602f0f6faf2072be9c0b995ee3d603f61414c4beb027b678c90946db6903a2

same as php code without pack. How can I achieve the same output as PHP, ie using the pack('H*', $secret) in Java code ?

Thanks to this stackoverflow answer by @rolfl, instead of string.getBytes java function on the secret key, I used his function to get the bytes,

    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;
    }

Now I get the same as php side for hex type secret key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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