Skip to content

Instantly share code, notes, and snippets.

@zinevych
Created April 11, 2023 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zinevych/8e01f7f1bd6cc21d5f6f89c89abef59f to your computer and use it in GitHub Desktop.
Save zinevych/8e01f7f1bd6cc21d5f6f89c89abef59f to your computer and use it in GitHub Desktop.
const crypto = require('crypto');
// Encrypt a message with a secret key
const message = 'This is a secret message';
const secretKey = 'This is a secret key';
// Create a 256-bit cipher key and initialization vector
const cipherKey = crypto.createHash('sha256').update(secretKey).digest();
const iv = crypto.randomBytes(16);
// Encrypt the message
const cipher = crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
let encryptedMessage = cipher.update(message, 'utf8', 'hex');
encryptedMessage += cipher.final('hex');
console.log('Encrypted message:', iv.toString('hex') + encryptedMessage);
// Decrypt the message
const encryptedBuffer = Buffer.from(iv.toString('hex') + encryptedMessage, 'hex');
const decipher = crypto.createDecipheriv('aes-256-cbc', cipherKey, encryptedBuffer.slice(0, 16));
let decryptedMessage = decipher.update(encryptedBuffer.slice(16), 'hex', 'utf8');
decryptedMessage += decipher.final('utf8');
console.log('Decrypted message:', decryptedMessage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment