How to make Android Java HMAC SHA256 like in PHP?… here is a solution to the problem.
How to make Android Java HMAC SHA256 like in PHP?
I have a snippet of PHP code:
$str=base64_encode('1234');
$key='1234';
print(base64_encode(hash_hmac('sha256', $str, $key,true)));
What is the code for Android Java (Android Studio)?
This code gives a different result than 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’t fix this; (
Maybe any restrictions on the Android platform or device?
Solution
You are converting the input string to base64, which is why it does not match. This is the 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;
}