7

I am porting a php script to node, and I don't know much about encryption.

The php script uses this function:

hash_hmac('sha512', text, key);

So, I need to implement a function in Node js for returning a keyed hash using the hmac method (SHA512).

From what I can see, node has this functionality built in via the crypto module (http://nodejs.org/docs/latest/api/crypto.html#crypto_crypto) -- But I unclear how to reproduce this function.

Any help would be appreciated.

Thanks,

1 Answer 1

9

Yes, use the crypto library.

var hash = crypto.createHmac('sha512', key);
hash.update(text);
var hashed_data = hash.digest();

More details (e.g. arguments to digest to control the output encoding from hash.digest) are at the link you provided.

As Nick points out, you will need to do this entire process each time you want to encrypt a new string (i.e. create a new hash object via crypto.createHmac.)

Sign up to request clarification or add additional context in comments.

2 Comments

Tip when using this, I think you can only call the digest() method on a hash once. This means that you cannot use update(), followed by digest() to form another hash. If you need to form multiple hashes, you will have to use crypto.createHmac() multiple times.
Yes, this is correct as far as I know. Thanks, I'll update my answer.

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.