Created
July 13, 2021 17:18
-
-
Save rebolyte/16b9d7dfa3b7dc76c65e9f848f238e1b to your computer and use it in GitHub Desktop.
This file contains hidden or 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"); | |
const algorithm = "aes-256-ctr"; | |
const password = "Password used to generate key"; | |
// Key length is dependent on the algorithm. In this case for aes192, it is | |
// 24 bytes (192 bits). For ae256, 32 bytes. | |
// Use async `crypto.scrypt()` instead. | |
const key = crypto.scryptSync(password, "salt", 32); | |
// Use `crypto.randomBytes()` to generate a random iv instead of the static iv | |
// shown here. | |
// const iv = Buffer.alloc(16, 0); // Initialization vector. | |
const iv = crypto.randomBytes(16).toString("hex").slice(0, 16); | |
const cipher = crypto.createCipheriv(algorithm, key, iv); | |
let encrypted = ""; | |
cipher.on("readable", () => { | |
let chunk;q | |
while (null !== (chunk = cipher.read())) { | |
encrypted += chunk.toString("hex"); | |
} | |
}); | |
cipher.on("end", () => { | |
console.log("encrypted:", encrypted); | |
// Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa | |
}); | |
cipher.write("some clear text data"); | |
cipher.end(); | |
// ------ | |
// ------ | |
// ------ | |
// ------ | |
// ------ | |
// ------ | |
// ------ | |
const decipher = crypto.createDecipheriv(algorithm, key, iv); | |
let decrypted = ""; | |
decipher.on("readable", () => { | |
while (null !== (chunk = decipher.read())) { | |
decrypted += chunk.toString("utf8"); | |
} | |
}); | |
decipher.on("end", () => { | |
console.log("decrypted:", decrypted); | |
// Prints: some clear text data | |
}); | |
// Encrypted with same algorithm, key and iv. | |
// const encrypted = "e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa"; | |
decipher.write(encrypted, "hex"); | |
decipher.end(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment