Skip to content

Instantly share code, notes, and snippets.

@ashutoshkarna03
Last active May 12, 2020 05:28
Show Gist options
  • Save ashutoshkarna03/5eb6127419c5848c584af5da9666a4ae to your computer and use it in GitHub Desktop.
Save ashutoshkarna03/5eb6127419c5848c584af5da9666a4ae to your computer and use it in GitHub Desktop.
'use strict';
const crypto = require('crypto');
const pool = require('./pg')
// const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY; // Must be 256 bits (32 characters)
// this is always stored in env file but for demonstration purpose, I have added it here
const ENCRYPTION_KEY = "bPeShVmYq3s6v9y$B&E)H@McQfTjWnZr"
const IV_LENGTH = 16; // For AES, this is always 16
// I am using AES-256-CBC algorithm with initialization vector (IV) of length 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();
}
// tests
let encryptedData = encrypt('myPassword')
console.log(encryptedData)
// now that we have encrypted password, we can insert this to database
// table structure is create table foo (id serial, password varchar)
pool.query(
`insert into foo (password) values ('${encryptedData}') ;`,
function (err, result) {
if (!err) {
console.log(result)
console.log('Insert complete')
} else {
console.log(err)
}
// let's read this data and decrypt it
pool.query(
"select password from foo where id = 2;",
function (err, result) {
if (!err) {
let encryptedPassword = result.rows[0].password
console.log(encryptedPassword)
let decryptedData = decrypt(encryptedPassword)
console.log('The decrypted Password: ')
console.log(decryptedData)
}
}
)
}
)
module.exports = { decrypt, encrypt };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment