Skip to content

Instantly share code, notes, and snippets.

@bbengfort
Last active December 20, 2021 01:13
Show Gist options
  • Save bbengfort/5807825 to your computer and use it in GitHub Desktop.
Save bbengfort/5807825 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());
@jadedfire
Copy link

In cipher-func.js you are using substr() incorrectly. Where you have substr(i, i+16), it should by substr(i, 16). The second param is the length of the substring, not the ending position.

@kebman
Copy link

kebman commented Aug 21, 2017

I wonder, would this be usable for generating an Ethereum wallet address / account?

@alakhirnayan
Copy link

wonderful ,, but why the setAutoPadding() is "False".. Please enable it...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment