Last active
June 9, 2017 08:31
-
-
Save joeywhelan/8758939 to your computer and use it in GitHub Desktop.
Node.js Crypto Module Examples
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
/** | |
* Joey Whelan | |
* 3 examples on usage of the node crypto module | |
*/ | |
var crypto = require('crypto'); | |
var plainText = '1234567812345678'; | |
try | |
{ | |
//Method 1 - Specify encoding on the cipher and do a string concat on the ciphertext. This works. | |
var cipher1 = crypto.createCipher('aes256', 'password'); | |
var cipherText1 = cipher1.update(plainText, 'ascii','binary'); | |
cipherText1 += cipher1.final('binary'); | |
console.log('Method 1 - plainText:' + plainText ); | |
console.log('Method 1 - cipherText length:' + cipherText1.length); | |
var decipher1 = crypto.createDecipher('aes256', 'password'); | |
var result1 = decipher1.update(cipherText1); | |
result1 += decipher1.final(); | |
console.log('Method 1 - result:' + result1); | |
//Method 2 - Use a Buffer object for the cipher text concatenation. This works. | |
var cipher2 = crypto.createCipher('aes256', 'password'); | |
var cipherText2 = Buffer.concat([cipher2.update(new Buffer(plainText)), cipher2.final()]); | |
console.log('Method 2 - plainText:' + plainText ); | |
console.log('Method 2 - cipherText length:' + cipherText2.length); | |
var decipher2 = crypto.createDecipher('aes256', 'password'); | |
var result2 = decipher2.update(cipherText2); | |
result2 += decipher2.final(); | |
console.log('Method 2 - result:' + result2); | |
//Method 3 - Don't specify any encoding on the cipher and do a string concat. This won't work. | |
var cipher3 = crypto.createCipher('aes256', 'password'); | |
var cipherText3 = cipher3.update(plainText); | |
cipherText3 += cipher3.final(); | |
console.log('Method 3 - plainText:' + plainText ); | |
console.log('Method 3 - cipherText length:' + cipherText3.length); | |
var decipher3 = crypto.createDecipher('aes256', 'password'); | |
var result3 = decipher3.update(cipherText3); | |
result3 += decipher3.final(); //Boom | |
console.log('Method 3 - result:' + result3); | |
} | |
catch (err) | |
{ | |
console.log(err.message); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment