Created
January 10, 2019 07:48
-
-
Save sedzd/8f90156f196bbb1c8357d6758638c6bb to your computer and use it in GitHub Desktop.
crypto encrypt decrypt class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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