Skip to content

Instantly share code, notes, and snippets.

@igez
Last active May 6, 2021 16:38
Show Gist options
  • Save igez/f8c7bebc7b6f68d733030dc66e149662 to your computer and use it in GitHub Desktop.
Save igez/f8c7bebc7b6f68d733030dc66e149662 to your computer and use it in GitHub Desktop.
import * as crypto from 'crypto';
export const CryptService = {
encrypt: (text: string) => {
if (text == null) {
return null;
}
try {
// random initialization vector
var iv = crypto.randomBytes(16);
// random salt
var salt = crypto.randomBytes(64);
// derive key: 32 byte key length - in assumption the masterkey is a cryptographic and NOT a password there is no need for
// a large number of iterations. It may can replaced by HKDF
var key = crypto.pbkdf2Sync(process.env.MASTER_KEY, salt, 2145, 32, 'sha512');
// AES 256 GCM Mode
var cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
// encrypt the given text
var encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
// extract the auth tag
// generate output
return Buffer.concat([salt, iv, encrypted]).toString('base64');
} catch(e) {
console.log("Failed to encrypt", text, e);
}
// error
return null;
},
/**
* Decrypts text by given key
* @param String base64 encoded input data
* @param Buffer masterkey
* @returns String decrypted (original) text
*/
decrypt: (data) => {
if (data == null) {
return null;
}
const base64Matcher = new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$");
if (!base64Matcher.test(data)) {
console.log('Invalid hash')
return null;
}
try {
// base64 decoding
var bData = Buffer.from(data, 'base64');
// convert data to buffers
var salt = bData.slice(0, 64);
var iv = bData.slice(64, 80);
// var tag = bData.slice(76, 92);
var text = bData.slice(80);
// derive key using; 32 byte key length
var key = crypto.pbkdf2Sync(process.env.MASTER_KEY, salt , 2145, 32, 'sha512');
// AES 256 GCM Mode
var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
// encrypt the given text
var decrypted = decipher.update(text, 'binary', 'utf8') + decipher.final('utf8');
return decrypted;
} catch(e) {}
// error
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment