Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asidpulse/859076c405de4365d71506b05765dce9 to your computer and use it in GitHub Desktop.
Save asidpulse/859076c405de4365d71506b05765dce9 to your computer and use it in GitHub Desktop.
nodejs crypto - simple encrypt & decrypt using IV (Initialization Vector)
"use strict";
var crypto = require("crypto");
var EncryptionHelper = (function () {
function getKeyAndIV(key, callback) {
crypto.pseudoRandomBytes(16, function (err, ivBuffer) {
var keyBuffer = (key instanceof Buffer) ? key : new Buffer(key) ;
callback({
iv: ivBuffer,
key: keyBuffer
});
});
}
function encryptText(cipher_alg, key, iv, text, encoding) {
var cipher = crypto.createCipheriv(cipher_alg, key, iv);
encoding = encoding || "binary";
var result = cipher.update(text, "utf8", encoding);
result += cipher.final(encoding);
return result;
}
function decryptText(cipher_alg, key, iv, text, encoding) {
var decipher = crypto.createDecipheriv(cipher_alg, key, iv);
encoding = encoding || "binary";
var result = decipher.update(text, encoding);
result += decipher.final();
return result;
}
return {
CIPHERS: {
"AES_128": "aes128", //requires 16 byte key
"AES_128_CBC": "aes-128-cbc", //requires 16 byte key
"AES_192": "aes192", //requires 24 byte key
"AES_256": "aes256" //requires 32 byte key
},
getKeyAndIV: getKeyAndIV,
encryptText: encryptText,
decryptText: decryptText
};
})();
module.exports = EncryptionHelper;
var assert = require('assert');
var encryptionHelper = require("./simple-nodejs-iv-encrypt-decrypt.js")
var story = "this is the story of the brave prince who went off to fight the horrible dragon... he set out on his quest one sunny day";
var algorithm = encryptionHelper.CIPHERS.AES_256;
console.log("testing encryption and decryption");
console.log("text is: " + story);
encryptionHelper.getKeyAndIV("1234567890abcdefghijklmnopqrstuv", function (data) { //using 32 byte key
console.log("got key and iv buffers");
var encText = encryptionHelper.encryptText(algorithm, data.key, data.iv, story, "base64");
console.log("encrypted text = " + encText);
var decText = encryptionHelper.decryptText(algorithm, data.key, data.iv, encText, "base64");
console.log("decrypted text = " + decText);
assert.equal(decText, story);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment