Skip to content

Instantly share code, notes, and snippets.

@briancw
Created December 20, 2017 01:40
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 briancw/485e2645f7da16eaa3b530dd913297a5 to your computer and use it in GitHub Desktop.
Save briancw/485e2645f7da16eaa3b530dd913297a5 to your computer and use it in GitHub Desktop.
Encryption Example
const crypto = require('crypto')
const owasp = require('owasp-password-strength-test')
owasp.config({
allowPassphrases: true,
maxLength: 128,
minLength: 16,
minPhraseLength: 24,
minOptionalTestsToPass: 4,
})
/**
* Generate a pbkdf2 key from a user password and salt
* @param {String} password A user entered password with will be used to derive a key
* @param {Buffer} salt Either a new salt for a new key or the old salt to re-generate an old key
* @return {Buffer} A buffer derived from the password
*/
function createKey(password, salt) {
const passwordStrength = owasp.test(password)
if (!passwordStrength.strong) {
throw new Error(passwordStrength.errors[0])
}
// const key = crypto.createHash('sha256').update(password).digest()
const key = crypto.pbkdf2Sync(password, salt, 10000, 32, 'sha512')
return key
}
/**
* Encrypt a data string with an encryption key
* @param {String} data The data to be encrypted
* @param {String} password A password to be used for encrypting
* @return {String} The encrypted data
*/
function encrypt(data, password) {
const iv = crypto.randomBytes(16)
const salt = crypto.randomBytes(32)
const key = createKey(password, salt)
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv)
let encrypted = cipher.update(data)
encrypted = Buffer.concat([encrypted, cipher.final()])
return [iv.toString('hex'), salt.toString('hex'), encrypted.toString('hex')].join(':')
}
/**
* Decryt data with the encryption key used to encrypt it
* @param {String} data The data to be decrypted
* @param {String} password A key to be used for encrypting
* @return {String} The decrypted data
*/
function decrypt(data, password) {
const textParts = data.split(':')
const iv = new Buffer(textParts[0], 'hex')
const salt = new Buffer(textParts[1], 'hex')
const encryptedText = new Buffer(textParts[2], 'hex')
const key = createKey(password, salt)
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv)
let decrypted = decipher.update(encryptedText)
decrypted = Buffer.concat([decrypted, decipher.final()])
return decrypted.toString()
}
module.exports = {
decrypt,
encrypt,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment