Created
October 15, 2018 17:05
-
-
Save mul14/3844155bde62ba8dfd1294e7f7a43fed to your computer and use it in GitHub Desktop.
Node.js v10 - crypto.createDecipheriv()
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
// 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