Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To use CryptoJs's AES for encryption and decryption in JavaScript, you need to follow these steps:

  1. Include the CryptoJS library in your HTML file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>
  1. Create a key and initialization vector (IV). The key is a secret value that is used to encrypt and decrypt data, while the IV is a random value that is used as the starting point for the encryption algorithm. For AES encryption, the key and IV must be in Base64 format.
var key = CryptoJS.enc.Base64.parse('SECRET_KEY');
var iv = CryptoJS.enc.Base64.parse('RANDOM_IV');
  1. Define the text you want to encrypt:
var plaintext = 'This is my secret message';
  1. Encrypt the plaintext using the key and IV:
var encrypted = CryptoJS.AES.encrypt(plaintext, key, { iv: iv });
var ciphertext = encrypted.toString();
  1. To decrypt the ciphertext back to plaintext, use the same key and IV:
var decrypted = CryptoJS.AES.decrypt(ciphertext, key, { iv: iv });
var plaintext = decrypted.toString(CryptoJS.enc.Utf8);

Note: make sure to keep the key and IV secret, as anyone with access to them can decrypt your encrypted data.