Skip to content

Symmetric Encryption & Decryption

Updated: at 06:22 AM

Table of Content

Symmetric Encryption

Example using Node.js

const crypto = require("crypto");

const key = crypto.randomBytes(32); // Generate a random 256-bit (32-byte) key
const iv = crypto.randomBytes(16); // Generate a random 128-bit (16-byte) initialization vector (IV)

Encryption

const data = "This is the data to be encrypted"; // Define the data to be encrypted
const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
let encrypted = cipher.update(data, "utf8", "hex");
encrypted += cipher.final("hex");
console.log(encrypted); // Outputs the encrypted data in hexadecimal format

Decryption

const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv); // <---
let decrypted = decipher.update(encrypted, "hex", "utf8");
decrypted += decipher.final("utf8");

console.log(decrypted); // Outputs the original data

Example using KMS (AWS)

const AWS = require("aws-sdk");
const kms = new AWS.KMS();

async function encryptData(keyId, plaintext) {
  const params = {
    KeyId: keyId,
    Plaintext: Buffer.from(plaintext),
  };

  try {
    const encrypted = await kms.encrypt(params).promise();
    return encrypted.CiphertextBlob;
  } catch (error) {
    console.error("Encryption error:", error);
    throw error;
  }
}

async function decryptData(ciphertextBlob) {
  const params = {
    CiphertextBlob: ciphertextBlob,
  };

  try {
    const decrypted = await kms.decrypt(params).promise();
    return decrypted.Plaintext.toString();
  } catch (error) {
    console.error("Decryption error:", error);
    throw error;
  }
}

const keyAlias = "alias/your-key-alias";
const sampleData = "Hello, world!";

(async () => {
  try {
    const encryptedData = await encryptData(keyAlias, sampleData);
    console.log("Encrypted Data:", encryptedData.toString("base64"));

    const decryptedData = await decryptData(encryptedData);
    console.log("Decrypted Data:", decryptedData);
  } catch (error) {
    console.error(error);
  }
})();