Yaroslav Snisar
Yaroslav Snisar

Reputation: 91

How make Android Java HMAC SHA256 as in PHP?

I have a code in PHP:

$str=base64_encode('1234');
$key='1234';
print(base64_encode(hash_hmac('sha256', $str, $key,true)));

And what code for Android Java (Android Studio)?

This code gives different result that in PHP:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

private String hash_hmac(String str, String secret) throws Exception{
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
byte[] string = str.getBytes();
String stringInBase64 = Base64.encodeToString(string, Base64.DEFAULT);
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secretKey);
String hash = Base64.encodeToString(sha256_HMAC.doFinal(stringInBase64.getBytes()), Base64.DEFAULT);
return hash;
}

String str = "1234";
String key = "1234";

try {

    Log.d("HMAC:", hash_hmac(str,key));

} catch (Exception e) {
    Log.d("HMAC:","stop");
    e.printStackTrace();
}

But in native Java it works fine. I can not resolve this ;( Maybe any limits for Android platform or device?

Upvotes: 4

Views: 4317

Answers (1)

Madan Gehlot
Madan Gehlot

Reputation: 99

You are converting your input string to base64 that's why it's not matching. here is correct code -

private String hash_hmac(String str, String secret) throws Exception{
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");

SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secretKey);
String hash = Base64.encodeToString(sha256_HMAC.doFinal(str.getBytes()), Base64.DEFAULT);
return hash;
}

Upvotes: 7

Related Questions