Database Secrets
Sometimes you need to store and retrieve secrets in database. Here we provide a way to encrypt and decrypt secrets:
const YepCodeDecryptor = require('./yepcode_decryptor')
const SECRET_SALT = '4d4d5625f75267f5'const SECRET_KEY = 'I-am-the-secret-of-all-your-passwords'const decryptor = new YepCodeDecryptor(SECRET_KEY, SECRET_SALT)
const encrypted = decryptor.encrypt(`foo`)const decrypted = decryptor.decrypt(encrypted)console.log('encrypted', encrypted)console.log('decrypted', decrypted)yepcode_decryptor.js
Section titled “yepcode_decryptor.js”const crypto = require('crypto');
const IV_LENGTH = 16;const ALGORITHM = 'AES-256-GCM';
const decrypt = (secretKey, encryptedTextHex) => { const cipher = Buffer.from(encryptedTextHex, 'hex'); const iv = cipher.slice(0, IV_LENGTH); const auth = cipher.slice(cipher.length - IV_LENGTH, cipher.length); const cipherText = cipher.slice(IV_LENGTH, cipher.length - IV_LENGTH); const decipher = crypto.createDecipheriv(ALGORITHM, secretKey, iv);
let decrypted = decipher.update(cipherText, null, 'utf8'); decipher.setAuthTag(auth); decrypted += decipher.final('utf8'); return decrypted;};
const encrypt = (secretKey, text) => { const iv = crypto.randomBytes(IV_LENGTH); const cipher = crypto.createCipheriv(ALGORITHM, secretKey, iv); let encrypted = cipher.update(text); encrypted = Buffer.concat([encrypted, cipher.final()]);
const tag = cipher.getAuthTag(); return Buffer.concat([iv, encrypted, tag]).toString('hex');};
/** * Aes decryptor. * * @param {*} secretKey * @param {*} salt */function YepCodeDecryptor( secretKey = process.env.ENCRYPTION_SECRET_KEY, salt = process.env.ENCRYPTION_SALT) { this._secretKey = crypto.pbkdf2Sync( secretKey, Buffer.from(salt, 'hex'), 1024, 32, 'sha1' );}
YepCodeDecryptor.prototype.decrypt = function (text) { return decrypt(this._secretKey, text);};
YepCodeDecryptor.prototype.encrypt = function (text) { return encrypt(this._secretKey, text);};
module.exports = YepCodeDecryptor;