1

I am trying to convert Java code to Node js to generate token using Hmac. Java code-

Mac mac = Mac.getInstance("HmacSHA256")
SecretKeySpec key = new SecretKeySpec(mysecret.getBytes("UTF-8","HmacSHA256")
mac.init(key)
byte[] hash = mac.doFinal(texttoEncode.getBytes(UTF-8))

Can anyone please suggest what will be its Javascript /node js equivalent.

1 Answer 1

4

The crypto built-in module provides createHmac method with the following signature:

crypto.createHmac(algorithm, key[, options])

To create a token:

const Crypto = require('crypto');

const token = Crypto.createHmac('sha256', 'a secret').update('data').digest('hex');

console.log(token); // 5da263f0f0ee86707c7c3f590d20066b7107e5ac70a41560926fa634bc78b137
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Adam, In Java code they are passing bytes array to dofinal, but in createhmac update we can only pass string. And the output is not same when I am passing string in update function
@bhanu, update accept a BinaryLike argument. You can create that DS using Buffer.
yeah, Crypto.createHmac('sha256', 'a secret').update('data').digest('hex') will get a string.if want a array , try Crypto.createHmac('sha256', 'a secret').update('data').digest() @bhanu
Thanks Adam passing buffer fixed the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.