Question

Execute HMAC SHA1 algorithm to encode string in binary

Hello,

I have a requirement of executing HMAC SHA1 algorithm to encode a string in binary. Could anybody please tell me how to convert string to binary using HMAC SHA1 algorithm?

Thanks!

Divya

Correct Answer
October 11, 2019 - 12:09am

Hello,

I have achieved this writing a function as below.

byte[] byteHMAC = null;

String result = null;

Charset ascii = Charset.forName("US-ASCII");

try 

{

   Mac mac = Mac.getInstance("HmacSHA1");

   SecretKeySpec spec;

            

   spec = new SecretKeySpec(Base64Util.decode(tokenSecret.getBytes(ascii)), "HmacSHA1");

            

   mac.init(spec);

   byteHMAC = mac.doFinal(baseString.getBytes(ascii));

  

  result = new String(Base64Util.encode(byteHMAC));

catch (InvalidKeyException e) 

{

   e.printStackTrace();

catch (NoSuchAlgorithmException ignore) 

{

   // should never happen

}

return result;

 

** here, baseString and tokenSecret are the parameters for the function

Comments

Keep up to date on this post and subscribe to comments

Pega
September 26, 2019 - 2:05am

Hi Divya,

Could you please refer the below post which shows the algorithm calculation and implementation.

https://stackoverflow.com/questions/7124735/hmac-sha256-algorithm-for-signature-calculation

October 11, 2019 - 12:09am

Hello,

I have achieved this writing a function as below.

byte[] byteHMAC = null;

String result = null;

Charset ascii = Charset.forName("US-ASCII");

try 

{

   Mac mac = Mac.getInstance("HmacSHA1");

   SecretKeySpec spec;

            

   spec = new SecretKeySpec(Base64Util.decode(tokenSecret.getBytes(ascii)), "HmacSHA1");

            

   mac.init(spec);

   byteHMAC = mac.doFinal(baseString.getBytes(ascii));

  

  result = new String(Base64Util.encode(byteHMAC));

catch (InvalidKeyException e) 

{

   e.printStackTrace();

catch (NoSuchAlgorithmException ignore) 

{

   // should never happen

}

return result;

 

** here, baseString and tokenSecret are the parameters for the function