Cryptography in React with CryptoJS

I was looking for way to encrypt a JWT token that's when I found out about an npm package crypto-js. This package is used for hashing & encryption. This is a guide how to use crypto-js.

1. Installation

npm install crypto-js

2. Import in JS file

import Cryptojs from 'crypto-js';

3. Encryption examples

***AES Encryption : * **

In this type of encryption, we generally use a 16 character key to encrypt the data in string format. For decryption, we have to use the same key.

function getAESEncryptedText(data,key){
    const encryptedData = Cryptojs.AES.encrypt(data,key);    
    //creates encrypted object for data using AES algorithm

    const encryptedText = encryptedData.toString();
    //converts AES encrypted object to string

    return encryptedText;
}

***AES Decryption : * **

function getAESDecryptedText(encryptedText,key){
    const decryptedData = Cryptojs.AES.decrypt(encryptedText,key);    
    //decrypts text which is encrypted using AES algorithm

    const decryptedText = encryptedData.toString(Cryptojs.enc.Utf8);
    //converts decrypted object to string of original value

    return decryptedText;
}

***MD5 Hashing : ***

function getMD5Text(data){
    const md5Data = Cryptojs.MD5(data);    
    //creates hash object for data using MD5

    const md5Text = md5Data.toString();
    //converts hash object to string

    return md5Text;
}

***SHA256 Hashing : ***

function getSHA256Text(data){
    const sha256Data = Cryptojs.SHA256(data);    
    //creates hash object for data using SHA256

    const sha256Text = sha256Data.toString();
    //converts hash object to string

    return sha256Text;
}

We can use multiple encryption algorithms and hashing techniques using this package.

Happy Coding!!

1
Subscribe to my newsletter

Read articles from Shubham Suryavanshi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shubham Suryavanshi
Shubham Suryavanshi