개발/NodeJS

[NodeJS] crypto 양방향 암호화 복호화

one-stone 2023. 8. 6. 01:41
const crypto = require('crypto');

const algorithm = 'aes-256-cbc';
const key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; // key (32 바이트)
const iv = 'bbbbbbbbbbbbbbbb'; // Initialization Vector (16 바이트)

function encrypt(text) {
  const cipher = crypto.createCipheriv('', key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;
}

function decrypt(encrypted) {
  const decipher = crypto.createDecipheriv(algorithm, key, iv);
  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

// 암호화
const plaintext = 'Hello, this is a secret message.';
const encryptedText = encrypt(plaintext);
console.log('Encrypted:', encryptedText);

// 복호화
const decryptedText = decrypt(encryptedText);
console.log('Decrypted:', decryptedText);