Skip to content

Instantly share code, notes, and snippets.

@mul14
Created October 15, 2018 17:05
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mul14/3844155bde62ba8dfd1294e7f7a43fed to your computer and use it in GitHub Desktop.
Save mul14/3844155bde62ba8dfd1294e7f7a43fed to your computer and use it in GitHub Desktop.
Node.js v10 - crypto.createDecipheriv()
// This is example of using crypto.createCipheriv(), because
// crypto.createCipher() is deprecated since Node.js v10
const crypto = require('crypto')
const encrypto = {
encrypt(text, password) {
const key = password.repeat(32).substr(0, 32)
const iv = password.repeat(16).substr(0, 16)
const cipher = crypto.createCipheriv('aes-256-ctr', key, iv)
let encrypted = cipher.update(text, 'utf8', 'hex')
encrypted += cipher.final('hex')
return encrypted
},
decrypt(text, password) {
const key = password.repeat(32).substr(0, 32)
const iv = password.repeat(16).substr(0, 16)
const decipher = crypto.createDecipheriv('aes-256-ctr', key, iv)
let decrypted = decipher.update(text, 'hex', 'utf8')
decrypted += decipher.final('utf8')
return decrypted
}
}
const message = 'Hello World!'
const key = 'p4$5w0rD'
const encryptedMessage = encrypto.encrypt(message, key)
console.log(encryptedMessage) // 17a26aa419b4b88609750b9f
console.log(encrypto.decrypt(encryptedMessage, key)) // Hello World!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment