javanode.jsrestcryptographyhmacsha1

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.


Solution

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