Created
August 14, 2015 10:56
-
-
Save manuks/5cef1e536ef791e97b39 to your computer and use it in GitHub Desktop.
Node js aes-256-cbc encryption and decryption
This file contains hidden or 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 keyhex = "8479768f48481eeb9c8304ce0a58481eeb9c8304ce0a5e3cb5e3cb58479768f4"; //length 32 | |
var blockSize = 16; | |
function encryptAES(input) { | |
try { | |
var iv = require('crypto').randomBytes(16); | |
//console.info('iv',iv); | |
var data = new Buffer(input).toString('binary'); | |
//console.info('data',data); | |
key = new Buffer(keyhex, "hex"); | |
//console.info(key); | |
var cipher = require('crypto').createCipheriv('aes-256-cbc', key, iv); | |
// UPDATE: crypto changed in v0.10 | |
// https://github.com/joyent/node/wiki/Api-changes-between-v0.8-and-v0.10 | |
var nodev = process.version.match(/^v(\d+)\.(\d+)/); | |
var encrypted; | |
if( nodev[1] === '0' && parseInt(nodev[2]) < 10) { | |
encrypted = cipher.update(data, 'binary') + cipher.final('binary'); | |
} else { | |
encrypted = cipher.update(data, 'utf8', 'binary') + cipher.final('binary'); | |
} | |
var encoded = new Buffer(iv, 'binary').toString('hex') + new Buffer(encrypted, 'binary').toString('hex'); | |
return encoded; | |
} catch (ex) { | |
// handle error | |
// most likely, entropy sources are drained | |
console.error(ex); | |
} | |
} | |
function decryptAES(encoded) { | |
var combined = new Buffer(encoded, 'hex'); | |
key = new Buffer(keyhex, "hex"); | |
// Create iv | |
var iv = new Buffer(16); | |
combined.copy(iv, 0, 0, 16); | |
edata = combined.slice(16).toString('binary'); | |
// Decipher encrypted data | |
var decipher = require('crypto').createDecipheriv('aes-256-cbc', key, iv); | |
// UPDATE: crypto changed in v0.10 | |
// https://github.com/joyent/node/wiki/Api-changes-between-v0.8-and-v0.10 | |
var nodev = process.version.match(/^v(\d+)\.(\d+)/); | |
var decrypted, plaintext; | |
if( nodev[1] === '0' && parseInt(nodev[2]) < 10) { | |
decrypted = decipher.update(edata, 'binary') + decipher.final('binary'); | |
plaintext = new Buffer(decrypted, 'binary').toString('utf8'); | |
} else { | |
plaintext = (decipher.update(edata, 'binary', 'utf8') + decipher.final('utf8')); | |
} | |
return plaintext; | |
} | |
var input="testing"; | |
var encrypted = encryptAES(input); | |
console.info('encrypted:', encrypted); | |
var decryped = decryptAES(encrypted); | |
console.info('decryped:',decryped); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Jk