I'm trying to port the following php code to javascript on node.js:
$mac = hash_hmac('SHA256', 'string', 'secret', true);
$coded = base64_encode($mac);
I've tried the following:
var Crypto = require('crypto');
var code = Crypto.util.bytesToBase64(Crypto.HMAC(Crypto.SHA256, 'string', 'secret', { asBytes: true }));
I get the error:
TypeError: Object #Object has no method 'HMAC'
I'm new to node.js, what am I doing wrong?
Update:
var code = Crypto.createHmac('SHA256', secret_key).update(to_encode).digest('base64');
Node. js provides a built-in module called crypto that you can use to encrypt and decrypt strings, numbers, buffers, streams, and more. This module offers cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.
To encrypt the message, use the update() method on the cipher . Pass the first argument as the message , the second argument as utf-8 (input encoding), and hex (output encoding) as the third argument.
Using Clean architecture for Node.NodeJS provides inbuilt library crypto to encrypt and decrypt data in NodeJS. We can use this library to encrypt data of any type. You can do the cryptographic operations on a string, buffer, and even a stream of data. The crypto also holds multiple crypto algorithms for encryption.
The Node. js Crypto module supports cryptography. It provides cryptographic functionality that includes a set of wrappers for open SSL's hash HMAC, cipher, decipher, sign and verify functions.
You want to use the createHmac
function instead.
Crypto.createHmac("SHA256", 'secret').update('string').digest('base64')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With