Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Last active April 9, 2024 15:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save montanaflynn/f0bd4c1fe58e28ce4d520bd1b84d2291 to your computer and use it in GitHub Desktop.
Save montanaflynn/f0bd4c1fe58e28ce4d520bd1b84d2291 to your computer and use it in GitHub Desktop.
Encrypt and decrypt text using AES with a shared key in nodejs
const crypto = require('crypto');
const password = 'password';
function encrypt(password, text) {
const algorithm = 'aes-256-ctr';
const key = Buffer.concat([Buffer.from(password), Buffer.alloc(32)], 32);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString('hex') + encrypted.toString('hex');
}
function decrypt(password, text) {
const algorithm = 'aes-256-ctr';
const key = Buffer.concat([Buffer.from(password), Buffer.alloc(32)], 32);
const iv = Buffer.from(text.substring(0, 32), 'hex');
const encryptedText = Buffer.from(text.substring(32), 'hex');
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
const encryptedText = encrypt(password, 'Montana Flynn')
const decryptedText = decrypt(password, encryptedText)
console.log(encryptedText)
// 792bc3507021447de9a232696e92d359
console.log(decryptedText)
// Montana Flynn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment