crypto 32 characers encryption node js

const crypto = require('crypto');

function encrypt(text, key) {
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
  let encrypted = cipher.update(text);
  encrypted = Buffer.concat([encrypted, cipher.final()]);
  return iv.toString('hex') + ':' + encrypted.toString('hex');
}

function decrypt(text, key) {
  const textParts = text.split(':');
  const iv = Buffer.from(textParts.shift(), 'hex');
  const encryptedText = Buffer.from(textParts.join(':'), 'hex');
  const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
  let decrypted = decipher.update(encryptedText);
  decrypted = Buffer.concat([decrypted, decipher.final()]);
  return decrypted.toString();
}

const secretMessage = 'This is a secret message!';
const encryptionKey = 'MySuperSecretKey';

const encryptedMessage = encrypt(secretMessage, encryptionKey);
console.log('Encrypted:', encryptedMessage);

const decryptedMessage = decrypt(encryptedMessage, encryptionKey);
console.log('Decrypted:', decryptedMessage);

Explanation:

  1. Import the crypto module in Node.js to access cryptographic functionalities.

  2. Create an encrypt function that takes plaintext and a key as input parameters. Inside the function: a. Generate a random initialization vector (IV) using crypto.randomBytes(16). IVs are used to ensure different ciphertexts are generated even if the same plaintext is encrypted multiple times with the same key. b. Create a cipher object using crypto.createCipheriv with the 'aes-256-cbc' algorithm, passing the key and IV as parameters. c. Encrypt the plaintext using the cipher's update method and concatenate it with the final ciphertext obtained from the final method. d. Return a string that combines the IV and encrypted text in hexadecimal format, separated by a colon.

  3. Create a decrypt function that takes the encrypted text and a key as input parameters. Inside the function: a. Split the input text into two parts using the colon (':') separator to separate the IV and encrypted text. b. Convert the IV string to a Buffer using Buffer.from with 'hex' encoding. c. Convert the encrypted text string to a Buffer using Buffer.from with 'hex' encoding. d. Create a decipher object using crypto.createDecipheriv with the 'aes-256-cbc' algorithm, passing the key and IV as parameters. e. Decrypt the encrypted text using the decipher's update method and concatenate it with the final decrypted plaintext obtained from the final method. f. Return the decrypted plaintext as a string.

  4. Define a secretMessage and an encryptionKey.

  5. Encrypt the secretMessage using the encrypt function with the encryptionKey and log the encrypted message to the console.

  6. Decrypt the encrypted message using the decrypt function with the encryptionKey and log the decrypted message to the console.