Skip to content

Instantly share code, notes, and snippets.

@leosuncin
Created August 10, 2017 22:42
Show Gist options
  • Save leosuncin/17fd1a503b2afa212aef9d4cbd4374ea to your computer and use it in GitHub Desktop.
Save leosuncin/17fd1a503b2afa212aef9d4cbd4374ea to your computer and use it in GitHub Desktop.
Encrypt and decrypt using crypto
const crypto = require('crypto')
const IV_LENGTH = 16
const KEY_LENGTH = 32
const ALGORITHM = 'aes-256-cbc'
const ENCODING = 'hex'
const _privates = Symbol('privates')
/**
* Encrypt and decrypt text
*
* @class Cipher
*/
class Cipher {
/**
* Creates an instance of Cipher.
*
* @param {String} encriptionKey A key to use for encription
* @param {Buffer} [iv = crypto.randomBytes(16)] Initialization vector
* @throws {TypeError} Will throw an exception if `encriptionKey` is undefined
* @memberof Cipher
*/
constructor(encriptionKey, iv = crypto.randomBytes(IV_LENGTH)) {
if (!encriptionKey) {
throw new TypeError('ENCRYPTION_KEY_REQUIRED')
}
this[_privates] = new Map()
this[_privates].set('iv', iv)
this[_privates].set('key', encriptionKey)
}
/**
* Encrypt a string
*
* @param {String} text String to encrypt
* @returns {String}
* @memberof Cipher
*/
encrypt(text) {
const cipher = crypto.createCipheriv(
ALGORITHM,
Buffer.alloc(KEY_LENGTH, this[_privates].get('key')),
this[_privates].get('iv')
)
let encrypted = cipher.update(text, 'utf-8', ENCODING)
encrypted += cipher.final(ENCODING)
return `${this[_privates].get('iv').toString(ENCODING)}:${encrypted}`
}
/**
* Decrypt a string
*
* @param {String} text String to decrypt
* @returns {String}
* @memberof Cipher
*/
decrypt(text) {
const [ivText, encryptedText] = text.split(':')
const iv = ivText ? new Buffer(ivText, ENCODING) : this[_privates].get('iv')
const encrypted = new Buffer(encryptedText, ENCODING)
const decipher = crypto.createDecipheriv(
ALGORITHM,
Buffer.alloc(KEY_LENGTH, this[_privates].get('key')),
iv
)
let decrypted = decipher.update(encrypted)
decrypted = Buffer.concat([decrypted, decipher.final()])
return decrypted.toString()
}
}
module.exports = Cipher
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment