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 module
const crypto = require("crypto");
// encrypt the message
function 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 decryption
function 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 data
const iv = crypto.randomBytes(16);
// secret key generate 32 bytes of random data
const securitykey = crypto.randomBytes(32);
// protected data
const secretMessage = "This is a secret message";
//AES encryption
const encrypted =
encrypt(secretMessage, securitykey, "base64", iv);
console.log("Encrypted message:", encrypted);
//AES decryption
const decrypted = decrypt(Buffer.
from(encrypted, "base64"), securitykey, "utf8", iv)
console.log("Decrypted string:", decrypted);
Output:
Example 2: AES 128 Encryption and Decryption
//AES 128 Encryption Demo Program
// crypto module
const crypto = require("crypto");
// encrypt the message
function encrypt(plainText, securitykey, outputEncoding) {
const cipher = crypto.
createCipheriv("aes-128-ecb", securitykey, null);
return Buffer.
concat([cipher.update(plainText), cipher.final()]).
toString(outputEncoding);
}
//AES decryption
function 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 data
const securitykey = crypto.randomBytes(16);
// protected data
const secretMessage = "This is a secret message";
//AES encryption
const encrypted =
encrypt(secretMessage, securitykey, "base64");
console.log("Encrypted message:", encrypted);
//AES decryption
const decrypted = decrypt(Buffer.
from(encrypted, "base64"), securitykey, "utf8")
console.log("Decrypted string:", decrypted);