Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encryption in nodejs

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');

like image 675
Alex Avatar asked Feb 06 '12 18:02

Alex


People also ask

What is encryption in NodeJS?

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.

How do I encrypt a message in NodeJS?

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.

How do I encrypt a NodeJS ID?

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.

Is cryptography supported in NodeJS?

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.


1 Answers

You want to use the createHmac function instead.

Crypto.createHmac("SHA256", 'secret').update('string').digest('base64')
like image 168
Tesserex Avatar answered Oct 14 '22 23:10

Tesserex