Last active
October 23, 2018 20:08
-
-
Save garenyondem/bdf42b9a3fe3f09929d36fe959ed8e37 to your computer and use it in GitHub Desktop.
Encrypt or decrypt strings in Node.js
This file contains 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'); | |
module.exports = class Encryptor { | |
constructor(encryptionKey) { | |
this.ENCRYPTION_KEY = encryptionKey.toString(); // Must be 256 bits (32 characters) | |
this.IV_LENGTH = 16; // For AES, this is always 16 | |
} | |
encrypt(text) { | |
let iv = crypto.randomBytes(this.IV_LENGTH); | |
let cipher = crypto.createCipheriv('aes-256-cbc', new Buffer.from(this.ENCRYPTION_KEY), iv); | |
let encrypted = cipher.update(text); | |
encrypted = Buffer.concat([encrypted, cipher.final()]); | |
return `${iv.toString('hex')}:${encrypted.toString('hex')}`; | |
} | |
decrypt(encrypted) { | |
let encryptedParts = encrypted.split(':'); | |
let iv = new Buffer.from(encryptedParts.shift(), 'hex'); | |
let encryptedText = new Buffer.from(encryptedParts.join(':'), 'hex'); | |
let decipher = crypto.createDecipheriv('aes-256-cbc', new Buffer.from(this.ENCRYPTION_KEY), iv); | |
let decrypted = decipher.update(encryptedText); | |
decrypted = Buffer.concat([decrypted, decipher.final()]); | |
return decrypted.toString(); | |
} | |
} |
This file contains 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
{ | |
"name": "encryptor", | |
"version": "1.1.0", | |
"author": "Garen Yöndem", | |
"license": "MIT" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment