Skip to content

Instantly share code, notes, and snippets.

@rao123dk
Created July 4, 2019 05:50
Show Gist options
  • Save rao123dk/937e32a8fef29c7799da03c12e12a10e to your computer and use it in GitHub Desktop.
Save rao123dk/937e32a8fef29c7799da03c12e12a10e to your computer and use it in GitHub Desktop.
const crypto = require('crypto');
const ENCRYPTION_KEY = "XwPp9xazJ0ku5CZnlmgAx2Dld8SHkAeT" //Must be 256 bits(32 byte) (32 characters)
const IV_LENGTH = 16; // For AES, this is always 16
function encrypt(text) {
let iv = crypto.randomBytes(IV_LENGTH);
let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString('hex') + ':' + encrypted.toString('hex');
}
function decrypt(text) {
let textParts = text.split(':');
let iv = Buffer.from(textParts.shift(), 'hex');
let encryptedText = Buffer.from(textParts.join(':'), 'hex');
let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
var inc = encrypt("IDontKnow@123");
console.log('anc: ', inc);
console.log(decrypt(inc))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment