Created
December 21, 2021 11:38
-
-
Save vipulwairagade/edb020e2203ff4ce5b404ef280a89515 to your computer and use it in GitHub Desktop.
Encrypt and Decrypt aes-256-ctr algorithm using crypto library in node.js
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
const crypto = require('crypto'), | |
algorithm = 'aes-256-ctr', | |
password = 'd6F3Efeq'; | |
function encrypt(chunk) { | |
var cipher, | |
result, | |
iv; | |
// Create an iv | |
iv = crypto.randomBytes(16); | |
// Create a new cipher | |
cipher = crypto.createCipheriv(algorithm, password, iv); | |
// Create the new chunk | |
result = Buffer.concat([iv, cipher.update(chunk), cipher.final()]); | |
return result; | |
} | |
function decrypt(chunk) { | |
var decipher, | |
result, | |
iv; | |
// Get the iv: the first 16 bytes | |
iv = chunk.slice(0, 16); | |
// Get the rest | |
chunk = chunk.slice(16); | |
// Create a decipher | |
decipher = crypto.createDecipheriv(algorithm, password, iv); | |
// Actually decrypt it | |
result = Buffer.concat([decipher.update(chunk), decipher.final()]); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment