Node.js - AES Encryption and Decryption Example
Advanced Encryption Standard is a symmetric encryption algorithm. AES encryption is used by the U.S. for securing sensitive but unclassified material, so we can say it is enough secure. It allows 128 bit, 192 bit and 256-bit encryption. Symmetric encryption is very fast as compared to asymmetric encryption and are used in systems such as database system.
The following illustration highlights how symmetric cryptography works:
Example 1: AES 256 Encryption and Decryption
//AES 256 Encryption Demo Program// crypto moduleconst crypto = require("crypto");
// encrypt the messagefunction encrypt(plainText, securitykey, outputEncoding, iv) { const cipher = crypto. createCipheriv("aes-256-cbc", securitykey, iv); return Buffer. concat([cipher.update(plainText), cipher.final()]). toString(outputEncoding);}
//AES decryptionfunction decrypt(cipherText, securitykey, outputEncoding, iv) { const cipher = crypto. createDecipheriv("aes-256-cbc", securitykey, iv); return Buffer. concat([cipher.update(cipherText), cipher.final()]). toString(outputEncoding);}
// generate 16 bytes of random dataconst iv = crypto.randomBytes(16);
// secret key generate 32 bytes of random dataconst securitykey = crypto.randomBytes(32);
// protected dataconst secretMessage = "This is a secret message";
//AES encryptionconst encrypted = encrypt(secretMessage, securitykey, "base64", iv);console.log("Encrypted message:", encrypted);
//AES decryptionconst decrypted = decrypt(Buffer. from(encrypted, "base64"), securitykey, "utf8", iv)console.log("Decrypted string:", decrypted);
Example 2: AES 128 Encryption and Decryption
//AES 128 Encryption Demo Program// crypto moduleconst crypto = require("crypto");
// encrypt the messagefunction encrypt(plainText, securitykey, outputEncoding) { const cipher = crypto. createCipheriv("aes-128-ecb", securitykey, null); return Buffer. concat([cipher.update(plainText), cipher.final()]). toString(outputEncoding);}
//AES decryptionfunction decrypt(cipherText, securitykey, outputEncoding) { const cipher = crypto. createDecipheriv("aes-128-ecb", securitykey, null); return Buffer. concat([cipher.update(cipherText), cipher.final()]). toString(outputEncoding);}
// secret key generate 16 bytes of random dataconst securitykey = crypto.randomBytes(16);
// protected dataconst secretMessage = "This is a secret message";
//AES encryptionconst encrypted = encrypt(secretMessage, securitykey, "base64");console.log("Encrypted message:", encrypted);
//AES decryptionconst decrypted = decrypt(Buffer. from(encrypted, "base64"), securitykey, "utf8")console.log("Decrypted string:", decrypted);