1

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 ?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.