Reputation: 3709
I have the following code in php:
$binKey = pack("H*", $keyTest);
$hmac = strtoupper(hash_hmac($pbx_hash, $msg, $binKey));
How can i achieve the same in android (java).
I have tried few methods available for hmac sha512 but the result of php snippet is different from that of mine.
Thanks in advance
Upvotes: 2
Views: 5865
Reputation: 11
You can see the answer to the same question here : java hmac/sha512 generation
I've searched for long time to see the correct answer. I give you the code, Maybe it will help someone else.
private String generateHMAC( String datas )
{
// final Charset asciiCs = Charset.forName( "utf-8" );
Mac mac;
String result = "";
try
{
final SecretKeySpec secretKey = new SecretKeySpec( DatatypeConverter.parseHexBinary(PayboxConstants.KEY), "HmacSHA512" );
mac = Mac.getInstance( "HmacSHA512" );
mac.init( secretKey );
final byte[] macData = mac.doFinal( datas.getBytes( ) );
byte[] hex = new Hex( ).encode( macData );
result = new String( hex, "ISO-8859-1" );
}
catch ( final NoSuchAlgorithmException e )
{
AppLogService.error( e );
}
catch ( final InvalidKeyException e )
{
AppLogService.error( e );
}
catch ( UnsupportedEncodingException e )
{
AppLogService.error( e );
}
return result.toUpperCase( );
}
Upvotes: 1
Reputation: 1112
You can check it with this one.In which i encrypt it using HmacSHA512 algorithm after that i encode it by using base64.
try {
String secret = "secret";
String message = "Message";
Mac sha_HMAC = Mac.getInstance("HmacSHA512");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA512");
sha_HMAC.init(secret_key);
String hash = Base64.encodeToString(sha_HMAC.doFinal(message.getBytes()), Base64.DEFAULT);
System.out.println(hash);
Log.e("string is ",hash);
}
catch (Exception e){
System.out.println("Error");
}
Upvotes: 2