Simple Encryption and Decryption in Javascript using CryptoJs

Table of contents

No heading

No headings in the article.

This method using CryptoJs library.

  1. Install CryptoJs in tour project

     npm install crypto-js
    
  2. Create function for encrypt

     // import CryptoJS from 'crypto-js'
    
     export const simpleEncrypt = (textWillEncrypt, strKey) => {
         // textWillEncrypt is something will encrypted
         // strKey is string key for connect encrypt and decrypt
    
         const textEcrypt = CryptoJS.AES.encrypt(textWillEncrypt, strKey).toString()
         return textEcrypt
     }
    
  3. Create function for decrypt

     // import CryptoJS from 'crypto-js'
    
     export function simpleDecrypt(textWillDecrypt, strKey) {
         // textWillDecrypt is something will decrypted
         // strKey is string key for connect encrypt and decrypt (must same with function encrypt
    
         const bytes = CryptoJS.AES.decrypt(textWillDecrypt, strKey)
         const originalDecryptText = bytes.toString(CryptoJS.enc.Utf8)
         return originalDecryptText
     }