Skip to content

Instantly share code, notes, and snippets.

@sedzd
Created January 10, 2019 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sedzd/8f90156f196bbb1c8357d6758638c6bb to your computer and use it in GitHub Desktop.
Save sedzd/8f90156f196bbb1c8357d6758638c6bb to your computer and use it in GitHub Desktop.
crypto encrypt decrypt class
const crypto = require('crypto');
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const algorithm = 'aes-256-cbc'
class Safe {
constructor(key, iv) {
this.key = key,
this.iv = iv
}
encrypt (text) {
let cipher = crypto.createCipheriv(algorithm, Buffer.from(this.key), this.iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return encrypted.toString('hex')
}
decrypt (text) {
let iv = Buffer.from(this.iv);
let encryptedTxt = Buffer.from(text, 'hex');
let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), iv);
let decrypted = decipher.update(encryptedTxt);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
};
}
module.exports = new Safe(key, iv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment