Skip to content

Instantly share code, notes, and snippets.

@gagantous
Forked from bbengfort/cipher-func.js
Created November 21, 2017 03:00
Show Gist options
  • Select an option

  • Save gagantous/b8dc7abc71355c84d21665fb5fccf64f to your computer and use it in GitHub Desktop.

Select an option

Save gagantous/b8dc7abc71355c84d21665fb5fccf64f to your computer and use it in GitHub Desktop.
Encrypting and decrypting aes128 ciphers with an initialization vector in node.js.
var crypto = require('crypto');
var secret = crypto.randomBytes(24);
function encrypt(plaintext) {
var cipher = crypto.createCipher('aes-256-cbc', secret);
cipher.setAutoPadding(false);
var ciphertext = '';
for (var i=0; i < plaintext.length; i+=16) {
ciphertext += cipher.update(plaintext.substr(i, i+16), 'utf8', 'base64');
}
return ciphertext.toString('base64');
}
function decrypt(ciphertext) {
var decipher = crypto.createDecipher('aes-256-cbc', secret);
decipher.setAutoPadding(false);
var plaintext = decipher.update(ciphertext, 'base64', 'utf8');
return plaintext.toString('utf8');
}
var ciphertext = encrypt(new Buffer("The secret crow ate the pie of the bear.").toString('utf8'));
console.log("Cipher text is: " + ciphertext);
console.log("Plain text is: " + decrypt(ciphertext));
var crypto = require('crypto');
var secret = crypto.randomBytes(16),
cipher = crypto.createCipheriv("aes128", secret, secret),
decipher = crypto.createDecipheriv("aes128", secret,secret);
cipher.setAutoPadding(false);
decipher.setAutoPadding(false);
var plaintext = "This is my super secret password";
var ciphertext = cipher.update(plaintext);
console.log("Cipher text is:");
console.log(ciphertext.toString());
var deciphertext = decipher.update(ciphertext);
console.log("");
console.log("Deciphered text is:");
console.log(deciphertext.toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment