Bibin Mathew
Bibin Mathew

Reputation: 213

How to change the Node JS HMAC signature creation to Java

I am very rarely use Java and I have an requirement of converting a function in Node.js which builds the HMAC signature for REST POST call to Java

Node JS function :

function buildSignature(buf, secret) {
    const hmac = crypto.createHmac('sha256', Buffer.from(secret, 'utf8'));
    hmac.update(buf);
    return hmac.digest('hex');
}

What I have currently done is:

Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
     SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
     sha256_HMAC.init(secret_key);

     String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
     System.out.println(hash);

This is not working out to be the same.

Upvotes: 4

Views: 1567

Answers (2)

Kapil Chauhan
Kapil Chauhan

Reputation: 1

  Mac sha256_HMAC;
  sha256_HMAC = Mac.getInstance("HmacSHA256");
  SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
  sha256_HMAC.init(secret_key);
  byte[] hash = sha256_HMAC.doFinal(payload.getBytes());
  return new String(Hex.encodeHex(hash));

Upvotes: 0

Ryan Leach
Ryan Leach

Reputation: 4470

It's my suspicion that hmac.digest('hex'); isn't base 64 encoded. I'd try converting the response of sha256_HMAC.doFinal(message.getBytes()) to hex instead.

How to convert a byte array to a hex string in Java? 's

The answer I would prefer there (since I use Guava in many projects) is

final String hex = BaseEncoding.base16().lowerCase().encode(bytes);

Adapted to your question would be

final String hash = BaseEncoding.base16().lowerCase().encode(sha256_HMAC.doFinal(message.getBytes()));

Upvotes: 1

Related Questions