Last active
December 2, 2019 17:11
-
-
Save gabefinch/c9002e1db6d0372ba0ce0b632ef0c44d 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
var crypto = require('crypto'); | |
const CRYPTO_KEY = 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ'; // Must be 256 bytes (32 characters) | |
const message = `I see a little silhouetto of a man, | |
Scaramouch, scaramouch will you do the fandango, | |
Thunderbolt and lightning very very frightening me, | |
Gallileo, Gallileo, | |
Gallileo, Gallileo, | |
Gallileo Figaro - magnifico` | |
const cryptoStr = encrypt(message); | |
console.log('cryptStr:', cryptoStr); | |
var decrypted = decrypt(cryptoStr); | |
console.log('decrypted:', decrypted); | |
function encrypt(text) { | |
const initVector = crypto.randomBytes(16); //Always 16 bytes with AES | |
const cipher = crypto.createCipheriv( | |
'aes-256-cbc', CRYPTO_KEY, initVector | |
); | |
const encrypted = Buffer.concat( | |
[cipher.update(text), cipher.final()] | |
); | |
return initVector.toString('hex') + encrypted.toString('hex'); | |
} | |
function decrypt(text) { | |
const inputBuffer = new Buffer(text, 'hex'); | |
const initVector = inputBuffer.slice(0,16); | |
const decipher = crypto.createDecipheriv( | |
'aes-256-cbc', CRYPTO_KEY, initVector | |
); | |
const encrypted = inputBuffer.slice(16); | |
let decrypted = Buffer.concat( | |
[decipher.update(encrypted), decipher.final()] | |
); | |
return decrypted.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment