Last active
January 25, 2017 15:28
-
-
Save imravichaudhary/5e8cd065c414c7cc3a1a0afea624cfdd to your computer and use it in GitHub Desktop.
Encryption and Decryption in Node.js v6.9.4 for buffer data
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 Promise = require('bluebird') | |
module.exports = { | |
encrypt: encrypt, | |
decrypt: decrypt | |
} | |
/** | |
* @function encrypt Encrypt the buffer data | |
* @param {Buffer} buffer - Represent the buffer data which needs to be encrypted | |
* @param {Object} config - Contains the algorithm and password used for encryption | |
* @return {Promise<Buffer>} - Promise to the encrypted buffer | |
*/ | |
function encrypt (buffer, config) { | |
return new Promise((resolve, reject) => { | |
try { | |
var cipher = crypto.createCipher(config.algorithm, config.password) | |
var crypted = cipher.update(buffer) | |
crypted = Buffer.concat([ crypted, cipher.final() ]) | |
resolve(crypted) | |
} catch (err) { | |
reject(err) | |
} | |
}) | |
} | |
/** | |
* @function decrypt Decrypt the buffer data | |
* @param {Buffer} buffer - Represent the buffer data which needs to be decrypted | |
* @param {Object} config - Contains the algorithm and password used for decryption | |
* @return {Promise<Buffer>} - Promise to the decrypted buffer | |
*/ | |
function decrypt (buffer, config) { | |
return new Promise((resolve, reject) => { | |
try { | |
var decipher = crypto.createDecipher(config.algorithm, config.password) | |
var decrypted = decipher.update(buffer) | |
decrypted = Buffer.concat([ decrypted, decipher.final() ]) | |
resolve(decrypted) | |
} catch (err) { | |
reject(err) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment