본문 바로가기

Javascript/Node.js

Node.js AES Encryption, Decryption

const crypto = require('crypto');

const algorithm = 'aes-128-cbc';
const secretKey = 'abcdefghijklmnop';
const iv = '00000000000000000000000000000000';

const encrypt = (message) => {
  const cipher = crypto.createCipheriv(algorithm, Buffer.from(secretKey), Buffer.from(iv, 'hex'));
  const encrypted = cipher.update(message);

  return Buffer.concat([encrypted, cipher.final()]).toString('hex');
};

const decrypt = (message) => {
  const decipher = crypto.createDecipheriv(algorithm, Buffer.from(secretKey), Buffer.from(iv, 'hex'));
  const decrypted = decipher.update(Buffer.from(message, 'hex'));

  return Buffer.concat([decrypted, decipher.final()]).toString();
};

const encrypted = encrypt('Hello World!');
console.log(`encrypted: ${encrypted}`);

const decrypted = decrypt(encrypted);
console.log(`decrypted: ${decrypted}`);