Skip to content

Instantly share code, notes, and snippets.

@sethdavis512
Created November 7, 2024 17:43
Show Gist options
  • Save sethdavis512/6f0fd8c234d2c6782f6eb2d7e5d99ed6 to your computer and use it in GitHub Desktop.
Save sethdavis512/6f0fd8c234d2c6782f6eb2d7e5d99ed6 to your computer and use it in GitHub Desktop.
async function encryptData(data, key) {
const encodedData = new TextEncoder().encode(data);
const iv = crypto.getRandomValues(new Uint8Array(12)); // Initialization vector
const encryptedData = await crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: iv
},
key,
encodedData
);
return { iv, encryptedData };
}
async function decryptData(encryptedData, key, iv) {
const decryptedData = await crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv
},
key,
encryptedData
);
return new TextDecoder().decode(decryptedData);
}
async function generateKey() {
return await crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256
},
true,
["encrypt", "decrypt"]
);
}
// Example usage
(async () => {
const key = await generateKey();
const data = "Hello, World!";
const { iv, encryptedData } = await encryptData(data, key);
console.log("Encrypted Data:", new Uint8Array(encryptedData));
const decryptedData = await decryptData(encryptedData, key, iv);
console.log("Decrypted Data:", decryptedData);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment