Last active
January 20, 2022 08:16
-
-
Save yoavniran/c78a0991e0152b306c25 to your computer and use it in GitHub Desktop.
nodejs crypto - simple encrypt & decrypt using IV (Initialization Vector)
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
"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; |
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
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); | |
}); |
ppbntl19
commented
Jun 9, 2020
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment