AES-GCM Encryption in JavaScript
Introduction
AES-GCM (Advanced Encryption Standard with Galois Counter Mode) is a robust encryption algorithm that provides both confidentiality and authenticity for data. It’s a popular choice for secure communication and data storage due to its efficiency and security.
This blog post will break down a JavaScript code snippet that demonstrates how to implement AES-GCM encryption. We’ll explore each function and its role in the overall process.
Generating the Encryption Key
The first step is to generate a key. This key is essential for signing and verifying messages.
async function generateKey() {
return await crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256,
},
true,
["encrypt", "decrypt"],
);
}
crypto.subtle.generateKey
: This method generates a cryptographic key.name: "AES-GCM"
: Specifies the algorithm to use (AES-GCM).length: 256
: Sets the key length to 256 bits, a commonly used secure length.true
: Indicates that the key can be exported for later use.["encrypt", "decrypt"]
: Defines the operations the key can be used for.
Encrypting Data
Once you have a key, you can use it to sign a message.
async function encrypt(key, data) {
const encoder = new TextEncoder();
const encodedData = encoder.encode(data);
const iv = crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await crypto.subtle.encrypt(
{
name: "AES-GCM",
iv,
},
key,
encodedData,
);
return { ciphertext, iv };
}
IV
: Initialization Vector is a random value that is used in conjunction with a secret key to initialize a block cipher mode of operation.TextEncoder
: Encodes the plaintext data into a Uint8Array for encryption.crypto.getRandomValues
: Generates a random initialization vector (IV) for the encryption process.crypto.subtle.encrypt
: Encrypts the encoded data using the generated key and IV.ciphertext, iv
: The encrypted data and IV are returned as a result.
Decrypting and Verifying Data
To verify a signature, you’ll need the key, ciphertext, iv and the original data.
async function decrypt(key, ciphertext, iv, originalData) {
const decoder = new TextDecoder();
const decryptedData = await crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv,
},
key,
ciphertext,
);
const decryptedText = decoder.decode(decryptedData);
return decryptedText === originalData;
}
TextDecoder
: Decodes the decrypted data back into a string.crypto.subtle.decrypt
: Decrypts the ciphertext using the key and IV.decryptedText === originalData
: Compares the decrypted text with the original data to verify integrity.
Example Usage
(async () => {
const key = await generateKey();
const data = "This is a secret message";
const { ciphertext, iv } = await encrypt(key, data);
const isValid = await decrypt(key, ciphertext, iv, data);
console.log("Data is valid:", isValid);
})();
- This code demonstrates how to use the functions defined earlier to encrypt, decrypt, and verify data.
- The
isValid
variable will betrue
if the decrypted data matches the original data.
Conclusion
AES-GCM provides a strong and efficient encryption method for securing data. By following the steps outlined in this blog post, you can effectively implement AES-GCM encryption in your JavaScript applications. Remember to handle key management carefully to ensure the security of your data.
Note: The IV
is typically a random value that is generated for each encryption operation, and it is used to ensure that the same plaintext will not result in the same ciphertext, even if the same key is used.
In the case of AES-GCM (Galois/Counter Mode), the IV is used to initialize the counter mode, which is a mode of operation that turns a block cipher into a stream cipher. The IV is used to generate a unique keystream for each encryption operation, which helps to prevent attacks that rely on predictable keystreams.
The IV is often prepended to the ciphertext, so that the recipient can use it to decrypt the message.
Further Reading
Latest blog posts
Explore the world of programming and cybersecurity through our curated collection of blog posts. From cutting-edge coding trends to the latest cyber threats and defense strategies, we've got you covered.