Created
April 11, 2023 20:52
-
-
Save zinevych/8e01f7f1bd6cc21d5f6f89c89abef59f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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