Skip to content

Instantly share code, notes, and snippets.

@tientp-floware
Created April 12, 2021 09:24
Show Gist options
  • Save tientp-floware/7303ea357725a950f1818d5a09d62d0e to your computer and use it in GitHub Desktop.
Save tientp-floware/7303ea357725a950f1818d5a09d62d0e to your computer and use it in GitHub Desktop.
New update nodejs above v10
import crypto = require('crypto');
export class CryptoAES {
private algorithm = 'aes-256-cbc';
private key: string;
private IV_LENGTH: number = 16;
private iv: Buffer; // random bytes
/**
* @example crytpo = new CryptoAES(<string 16,32 bits>) {Class object}
* @param key
*/
constructor(key) {
if(!key) throw new Error('Key can not be empty');
this.key = key;
this.iv = crypto.randomBytes(this.IV_LENGTH);
}
/**
* encrypt
*
* @param {String} message
* @example self.encrypt('some secret'); {String}
* @return {String} encrypted
*/
encrypt(message: string) {
let cipher = crypto.createCipheriv(this.algorithm, Buffer.from(this.key, 'base64'), this.iv);
let encrypted = cipher.update(message);
encrypted = Buffer.concat([encrypted, cipher.final()]);
// return format base64
return this.iv.toString('base64') + ':' + encrypted.toString('base64');
}
/**
* decrypt
*
* @param {String} encrypted
* @example self.encrypted(5IDMv3w1g68HqbFrCXzKyQ==:/oq12uZIyEB21ClDM3CJjAfcTEz7f8+H+UT+); {String}
* @return {String} decrypted
*/
decrypt(encrypted:string) {
// split to array
let textParts = encrypted.split(':');
// get iv in encrypted
let iv = Buffer.from(textParts.shift(), 'base64');
let encryptedText = Buffer.from(textParts.join(':'), 'base64');
let decipher = crypto.createDecipheriv(this.algorithm, Buffer.from(this.key, 'base64'), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
// to encode base64
return decrypted.toString();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment