Created
November 7, 2024 17:43
-
-
Save sethdavis512/6f0fd8c234d2c6782f6eb2d7e5d99ed6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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