Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PHP hash_hmac(sha512) to NodeJS

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,

like image 889
user1031947 Avatar asked Mar 13 '13 19:03

user1031947


People also ask

How to create a SHA-256 hash in Node JS?

Blog About MENU How to create a SHA-256 hash in Node.js? Published November 14, 2020 To create a SHA-256hash, you need to import or require the cryptomodule and use the createHmac()method in Node.js. Skip to the full code First, let's require the cryptomodule in Node.js, // get crypto moduleconstcrypto = require("crypto");

How to create a hash from a string in NodeJS?

To create a hash from strings you just need a few lines in nodejs: The great thing about the nodejs implementation of Hash is the possibility to stream data directly into the hash: Happy Hashing. If you have any questions contact me via Twitter @chri_hartmann or Github Ready for ES6?

What is hash_HMAC () in PHP?

The hash_hmac() function is an inbuilt function in PHP which is used to generate the keyed hash value using the HMAC method. Syntax: string hash_hmac( $algo, $msg, $key, $raw_opt )

What is the output format of the hash in the update() method?

It is called update()since it also accepts a continuous stream of data like a buffer. Finally, after calling the update()method we need to define the output format for the hash. It can be hex, binary, or base64. We can define it using the digest()method on the object returned from the update()method like so,


1 Answers

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.)

like image 168
Jacob Parker Avatar answered Sep 30 '22 17:09

Jacob Parker