Encrypt and Decrypt function using Crypto

var crypto = require(‘crypto’);

const cryptoKey = “mediumblogisthebestfordevelopmen”;

function encryptString(text) {

const iv = crypto.randomBytes(16);

const cipher = crypto.createCipheriv(‘aes-256-cbc’, new Buffer.from(cryptoKey), iv);

let encrypted = cipher.update(text);

encrypted = Buffer.concat([encrypted, cipher.final()]);

return iv.toString(‘hex’) + ‘:’ + encrypted.toString(‘hex’);

}

function encryptedTokenForEmail(payoutsList, userEmail) {

const result = _.map(payoutsList, function (mPayout) { return mPayout._id.toString(); });

const payoutText = result.join(‘;’);

console.log(“payoutText”,payoutText);

const contentString = [payoutText, userEmail];

return encryptString(contentString.join(‘:’));

}

function decryptString(text) {

const textParts = text.split(‘:’);

const iv = new Buffer.from(textParts.shift(), ‘hex’);

const encryptedText = new Buffer.from(textParts.join(‘:’), ‘hex’);

const decipher = crypto.createDecipheriv(‘aes-256-cbc’, new Buffer.from(cryptoKey), iv);

let decrypted = decipher.update(encryptedText);

decrypted = Buffer.concat([decrypted, decipher.final()]);

return decrypted.toString();

}

function decryptedValueFromEmail(token) {

const decryptedText = decryptString(token);

const mainContentSplit = decryptedText.split(‘:’);

const payoutIds = mainContentSplit[0].split(‘;’);

return {

payoutIds,

userEmail: mainContentSplit[1]

};

}

module.exports.encryptString = encryptString;

module.exports.encryptedTokenForEmail = encryptedTokenForEmail;

module.exports.decryptString = decryptString;

module.exports.decryptedValueFromEmail = decryptedValueFromEmail;

--

--