2

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

James Webster
  • 31,873
  • 11
  • 70
  • 114
Najeebullah Shah
  • 4,164
  • 4
  • 35
  • 49

2 Answers2

2

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");
        }
Vishwa
  • 1,112
  • 1
  • 11
  • 23
  • Thanks for the answer. But this code is giving different result of the same message as compared to the php one which i mentioned in my questions. I guess there is problem with this line: $binKey = pack("H*", $keyTest); – Najeebullah Shah Aug 05 '15 at 05:24
  • may be because encryption alogrithm has HMACsha256 and HMACsha512 – Vishwa Aug 05 '15 at 10:01
1

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( );

}
Community
  • 1
  • 1
Chewby
  • 11
  • 1