Table of Content
Symmetric Encryption
- Symmetric encryption is a type of encryption where the same key is used for both encryption and decryption. In other words, the sender and the receiver use the same secret key to encrypt and decrypt data. The most common types of symmetric encryption algorithms are AES, DES, and 3DES.
- Symmetric encryption can be used to
- encrypt data sent between two computers
- encrypt data stored on a hard drive or USB drive.
- Symmetric encryption is also commonly used to encrypt data in transit, such as through HTTPS, where a shared key is used to encrypt the data and provide secure communication over the internet.
- One disadvantage of symmetric encryption is that if the key is compromised, all encrypted data is vulnerable to attack. Therefore, securely sharing the key is a critical component of using symmetric encryption. This is often achieved using key exchange algorithms, such as the Diffie-Hellman key exchange.
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);
}
})();