AES Encryption in JavaScript
Let's Encrypt

AES (Advanced Encryption Standard) is a widely used symmetric encryption algorithm that uses a fixed-length key to encrypt and decrypt data. In JavaScript, you can use the crypto module in the Node.js runtime to perform AES encryption and decryption.


Here is an example of how to perform AES encryption in JavaScript using the crypto module:

const crypto = require('crypto');


const algorithm = 'aes-256-cbc';

const key = 'abcdefghijklmnopqrstuvwxyz012345';

const iv = 'abcdefghijklmnop';


function encrypt(text) {

  const cipher = crypto.createCipheriv(algorithm, key, iv);

  let encrypted = cipher.update(text, 'utf8', 'hex');

  encrypted += cipher.final('hex');

  return encrypted;

}


function decrypt(text) {

  const decipher = crypto.createDecipheriv(algorithm, key, iv);

  let decrypted = decipher.update(text, 'hex', 'utf8');

  decrypted += decipher.final('utf8');

  return decrypted;

}


const text = 'Hello, world!';

const encrypted = encrypt(text);

console.log(encrypted);  // '6d79477261706865322b576964744170'

const decrypted = decrypt(encrypted);

console.log(decrypted);  // 'Hello, world!'



In this example, we are using the aes-256-cbc algorithm, which uses a 256-bit key and a cipher block chaining (CBC) mode of operation.


The key and initialization vector (IV) must be specified as Buffers or strings of the appropriate length. The encrypt() function takes a string as input and returns the encrypted version as a hexadecimal string. The decrypt() function takes a hexadecimal string as input and returns the decrypted version as a string.


It is important to note that the crypto module uses a random initialization vector (IV) by default, so the IV does not need to be specified when calling the createCipher() or createCipheriv() functions.

However, in the example above, we have specified a fixed IV for the purposes of demonstration.

I hope this helps! Let me know if you have any questions.


AES Encryption in JavaScript
Administrator 27 December, 2022
Share this post
Archive