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 crypt strings in order to hide texts to users but in a way that allows me to decrypt and retrieve the original content. In this case a fast tool is Crypto.

Install:

npm install crypto

To encrypt and decrypt a string:

var crypto = require('crypto');

var cypherKey = "mySecretKey";

function encrypt(text){
  var cipher = crypto.createCipher('aes-256-cbc', cypherKey)
  var crypted = cipher.update(text,'utf8','hex')
  crypted += cipher.final('hex');
  return crypted; //94grt976c099df25794bf9ccb85bea72
}

function decrypt(text){
  var decipher = crypto.createDecipher('aes-256-cbc',cypherKey)
  var dec = decipher.update(text,'hex','utf8')
  dec += decipher.final('utf8');
  return dec; //myPlainText
}

3. Asymmetric encryption

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