JavaScript String Encryption and Decryption

Harshit Jindal Oct 12, 2023
  1. Use CryptoJS to Encrypt and Decrypt a JavaScript String
  2. Use NcryptJs to Encrypt and Decrypt a JavaScript String
JavaScript String Encryption and Decryption

This tutorial teaches how to encrypt and decrypt a JavaScript string.

Use CryptoJS to Encrypt and Decrypt a JavaScript String

CryptoJS is a JavaScript library containing implementations of standard and secure cryptographic algorithms. It is swift and provides a straightforward interface. It has support for hashers, ciphers, HMAC, PBKDF2, etc. Ciphers are used to encrypt/ decrypt JavaScript Strings. We will use the AES(Advanced Encryption Standard) algorithm, one of the most popular and widely adopted symmetric encryption algorithm. It is effortless to use the AES algorithm through CryptoJs’s interface. We have to call CryptoJS.AES.encrypt or CryptoJS.AES.decrypt depending on what we want to do and pass in the message to be encrypted/decrypted along with a secret key used in the algorithm.

var encrypted =
    CryptoJS.AES.encrypt('This is my secret message', 'EncryptionKey');
var decrypted = CryptoJS.AES.decrypt(encrypted, 'EncryptionKey');

Use NcryptJs to Encrypt and Decrypt a JavaScript String

NcryptJs is a lightweight library used to perform encryption and decryption in JavaScript. It implements Nodejs crypto functionality as a mid-channel cipher. It has two functions encrypt() and decrypt(). They use the AES-256-CBC algorithm. We can encrypt/decrypt a string simply by calling ncrypt.encrypt()/ncrypt.decrypt(). It also takes the message and secret key as the arguments. But it has an added advantage that we do not have to provide that secret key at the time of decryption.

import ncrypt from 'ncrypt-js';
const encrypted = ncrypt.encrypt('This is my secret message', 'Secret key');
console.log(encrypted);
const decrypted = ncrypt.decrypt(encrypted);
console.log(decrypted);
Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn

Related Article - JavaScript String