R
R
rustem_ck2017-06-12 10:19:25
PHP
rustem_ck, 2017-06-12 10:19:25

Why in Android Java and PHP HMAC SHA 256 results are different?

Can't figure out why:
Android Java:

private hash_hmac(String str, String secret){
    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
    sha256_HMAC.init(secretKey);
    String hash1 = Base64.encodeToString(sha256_HMAC.doFinal(str.getBytes("UTF-8")), 0);
        return hash1;
    }

Variables:
str = "eyJoYXNoIjoic29tZVJlcUhhc2hTdHIiLCJhbnN3ZXIiOnRydWV9"
    secret = "AusVwlqhJY4YvuCIdotMpduVWWQdiVnl"

Result:
UuJhaD7sjLXUPN01JJWEcObIwDdLXHturBdSZFxKPxI=
and in PHP:
$str=base64_encode('eyJoYXNoIjoic29tZVJlcUhhc2hTdHIiLCJhbnN3ZXIiOnRydWV9');
    $key='AusVwlqhJY4YvuCIdotMpduVWWQdiVnl';
    print(base64_encode(hash_hmac('sha256', $str, $key,true)));

Result:
AWFG4WXHtOToeN8d4J4Lt67u8VVa35AxBfIEsg31DhU=
Different results. I can't figure out why. At the same time, in desktop JAVA it coincides with PHP, but not in Android.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Talalaev, 2017-06-13
@rustem_ck

According to Stackoverflow , there is a difference in the string handler on Android in Java, in order to work the same way as on the desktop, you need to add the Base64.NO_WRAP key

Base64.encode("foobar".getBytes(), Base64.NO_WRAP);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question