DEV Community

stemword
stemword

Posted on

How to Encrypt and Decrypt in Node JS using Crypto

In this article, you’ll learn how to use the Node.js crypto module to perform cryptographic operations on data. I'll show you how to encrypt data with a secret key and then decrypt it using the same secret key when required.
You can also check video on YouTube.
https://www.youtube.com/watch?v=9PL7EK4jXLM

Create a new project

Create a new directory in your local file system and switch to it by typing the following

mkdir encr_decr && cd encr_decr
npm init -y
Enter fullscreen mode Exit fullscreen mode

Now install the crypto module

npm install crypto --save
Enter fullscreen mode Exit fullscreen mode

Now make app.js.

Add following code to app.js

var Crypto = require('crypto');
var secret_key = 'fd85b494-aaaa';
var secret_iv = 'smslt';
var encryptionMethod = 'AES-256-CBC';
var key = Crypto.createHash('sha512').update(secret_key, 'utf-8').digest('hex').substr(0, 32);
var iv = Crypto.createHash('sha512').update(secret_iv, 'utf-8').digest('hex').substr(0, 16);
var encryptedMessage = encrypt_string("hello", encryptionMethod, key, iv);
console.log(encryptedMessage); 
// output : L2dOZjlDVmxoSDNWdmpVMkNGd0JEdz09
var decrptMessage = decrypt_string(encryptedMessage, encryptionMethod, key , iv);
console.log(decrptMessage);  
//output : hello

function encrypt_string(plain_text, encryptionMethod, secret, iv) {
  var encryptor = Crypto.createCipheriv(encryptionMethod, secret, iv);
  var aes_encrypted = encryptor.update(plain_text, 'utf8', 'base64') + encryptor.final('base64');
  return Buffer.from(aes_encrypted).toString('base64');
};

function decrypt_string(encryptedMessage, encryptionMethod, secret, iv) {
  const buff = Buffer.from(encryptedMessage, 'base64');
  encryptedMessage = buff.toString('utf-8');
  var decryptor = Crypto.createDecipheriv(encryptionMethod, secret, iv);
  return decryptor.update(encryptedMessage, 'base64', 'utf8') + decryptor.final('utf8');
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, we looked at how to perform cryptographic operations on a text by using Node.js built-in crypto module.

Top comments (0)