Skip to content

How to encrypt and decrypt in nodejs

Published:

In my projects, I leverage two key cryptographic techniques for securing strings:

1. Hash functions with Bcrypt (one-way)

Hash functions are essentials for store encrypted password, and the best library for nodejs is Bcrypt. Why use Bcrypt?

Install:

npm install bcrypt

To hash a password:

const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 'myPassword';

bcrypt.hash(myPlaintextPassword, saltRounds).then((hash) => {
	// Store hash in your DB.
});

At user login to compare password with the one stored in the db you can use:

bcrypt.compare(plaintextPassToCheck, hashStoredInDB).then((res) => {
  if(res === true){
    //give access to the user
  }
});

More info: github.com/kelektiv/node.bcrypt.js

2. Simple Encryption and Decryption (two-way)

In other scenarios I needed to encrypt strings in order to hide text from users but in a way that allows me to decrypt and retrieve the original content. The Node.js built-in crypto module provides this functionality (no installation needed).

To encrypt and decrypt a string using AES-256-CBC with a random initialization vector (IV):

const crypto = require('crypto');

const ENCRYPTION_KEY = crypto.randomBytes(32); // 256-bit key
const IV_LENGTH = 16;

function encrypt(text) {
  const iv = crypto.randomBytes(IV_LENGTH);
  const cipher = crypto.createCipheriv('aes-256-cbc', ENCRYPTION_KEY, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return iv.toString('hex') + ':' + encrypted;
}

function decrypt(text) {
  const parts = text.split(':');
  const iv = Buffer.from(parts.shift(), 'hex');
  const encryptedText = parts.join(':');
  const decipher = crypto.createDecipheriv('aes-256-cbc', ENCRYPTION_KEY, iv);
  let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

Note: The older crypto.createCipher() and crypto.createDecipher() methods are deprecated since Node.js 10. Always use createCipheriv / createDecipheriv with an explicit IV for security.

3. Asymmetric encryption

If you want to use private and public key to encrypt your strings, you can follow this article.