Copy-Paste-Run-Ready string encryption / decryption with AES-256 in Node.JS
/* --- Code ready to copy -> paste -> run --- */
// Libraries
const crypto = require('crypto');
const ENCODING = "hex"; // hex or base64
// Implementations
function encryptAES256(clearMsg, key) {
let iv = crypto.randomBytes(16); // Generating 16 byte random IV
let cipher = crypto.createCipheriv(
"aes256",
crypto.createHash("sha256").update(key, "utf8").digest(), // 32 bytes always for the key
iv);
return (Buffer.concat([
iv, // Adding the IV at the beginning of the encrypted message (https://nodejs.org/dist/latest-v16.x/docs/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv_options)
cipher.update(clearMsg),
cipher.final()
])).toString(ENCODING);
}
function decryptAES256(encMsg, key) {
let decipher = crypto.createDecipheriv(
"aes256",
crypto.createHash("sha256").update(key, "utf8").digest(), // 32 bytes always for the key
Buffer.from(encMsg, ENCODING).slice(0, 16) // Extracting the IV from the encrypted string (16 bytes)
);
return (Buffer.concat([
decipher.update(Buffer.from(encMsg, ENCODING).slice(16)), // Extracting the encrypted message from the encrypted string
decipher.final()
])).toString('utf8');
}
// Exporting the functions to use it as a module
// module.exports.encryptAES256 = encryptAES256;
// module.exports.decryptAES256 = decryptAES256;
// Demo / Test
let e = encryptAES256("Hello World!", "test");
console.log("> Encrpyted: " + e);
let d = decryptAES256(e, "test");
console.log("> Decrpyted: " + d);
Sample output:
> Encrpyted: 0e5cf8a690a300c4e5dbdad1f168aa0a35a0762b122654dc82547eaa8fc8d430
> Decrpyted: Hello World!