Skip to content

Instantly share code, notes, and snippets.

@tuliofaria
Created December 11, 2017 00:05
Show Gist options
  • Save tuliofaria/b66199f7f23f1b4490560ddd27394ae0 to your computer and use it in GitHub Desktop.
Save tuliofaria/b66199f7f23f1b4490560ddd27394ae0 to your computer and use it in GitHub Desktop.
Crypt-with-iv
const crypto = require('crypto')
const alg = 'aes-256-ctr'
const pwd = 'abcdabcdabcdabcdabcdabcdabcdabcd'
function crypt(text){
const iv = crypto.randomBytes(16)
const cipher = crypto.createCipheriv(alg, pwd, iv)
const crypted = cipher.update(text, 'utf8', 'hex') + cipher.final('hex')
return iv.toString('hex')+':'+crypted
}
function decrypt(text){
const parts = text.split(':')
const decipher = crypto.createDecipheriv(alg, pwd, new Buffer(parts[0], 'hex'))
const plain = decipher.update(parts[1], 'hex', 'utf8') + decipher.final('utf8')
return plain
}
const text = 'tulio faria devpleno'
const criptografado1 = crypt(text)
const criptografado2 = crypt(text)
const criptografado3 = crypt(text)
console.log(text, '<< criptografado >>', criptografado1)
console.log(text, '<< criptografado >>', criptografado2)
console.log(text, '<< criptografado >>', criptografado3)
console.log(criptografado1, '<< em texto >>', decrypt(criptografado1))
console.log(criptografado2, '<< em texto >>', decrypt(criptografado2))
console.log(criptografado3, '<< em texto >>', decrypt(criptografado3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment