Skip to content

Instantly share code, notes, and snippets.

@arifineu
Last active January 24, 2024 01:26
Show Gist options
  • Save arifineu/136cddf49fe8de84f2537172be673605 to your computer and use it in GitHub Desktop.
Save arifineu/136cddf49fe8de84f2537172be673605 to your computer and use it in GitHub Desktop.
Encrypt and Decrypt using AES-256-CBC in node environment
import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto'
// Secret key and IV
const key = randomBytes(32) // 32 bytes for AES-256
const iv = randomBytes(16) // 16 bytes IV
// Encrypt function
function encrypt(text) {
// Create a cipher instance using the AES-256-CBC algorithm with the declared key, and iv
const cipher = createCipheriv('aes-256-cbc', key, iv)
// Encrypt the text
const encrypted = Buffer.concat([cipher.update(text), cipher.final()])
// Return the encrypted iv and text and convert it to hex string, so you can read it
return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') }
}
// Decrypt function
function decrypt(encryptedText) {
// Convert the hexadecimal IV back into a buffer
const ivBuffer = Buffer.from(encryptedText.iv, 'hex')
// Convert the hexadecimal encrypted data back into a buffer
const encryptedData = Buffer.from(encryptedText.encryptedData, 'hex')
// Create a decipher instance using the same algorithm and key as the encryption, and the IV from the encrypted text
const decipher = createDecipheriv('aes-256-cbc', key, ivBuffer)
// Decrypt the text, finalize, and return it
return Buffer.concat([decipher.update(encryptedData), decipher.final()]).toString()
}
// Example usage
const text = "Hello World!"
const encrypted = encrypt(text)
console.log('Encrypted:', encrypted)
const decrypted = decrypt(encrypted)
console.log('Decrypted:', decrypted)
// Important notes and points:
// 1. Make sure that the key and IV are securely generated and stored. Never hard code it in a real application.
// 2. Add error handling for production code.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment