JavaScript String Encryption and Decryption

  1. Use CryptoJS to Encrypt and Decrypt a JavaScript String
  2. Use NcryptJs to Encrypt and Decrypt a JavaScript String

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');
const decrypted = ncrypt.decrypt(encrypted);
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript String

  • Covert a String Into a Date in Javascript
  • JavaScript Insert Variable Into String