Last active
November 21, 2024 14:51
-
-
Save NikaBuligini/5063f64d1975c77f6cd7b4035f4e28b4 to your computer and use it in GitHub Desktop.
Encryption
This file contains hidden or 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
// objectKey, encrypted | |
const decryptKey = await crypto.subtle.importKey( | |
"jwk", | |
{ | |
k: objectKey, | |
alg: "A128GCM", | |
ext: true, | |
key_ops: ["decrypt"], | |
kty: "oct", | |
}, | |
{ name: "AES-GCM", length: 128 }, | |
false, // extractable | |
["decrypt"], | |
); | |
const decrypted = await crypto.subtle.decrypt( | |
{ name: "AES-GCM", iv: new Uint8Array(12) }, | |
decryptKey, | |
encrypted, | |
); | |
const decoded = new TextDecoder().decode(new Uint8Array(decrypted)); | |
console.log(decoded); // '{"foo":"bar"}' |
This file contains hidden or 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
const key = await crypto.subtle.generateKey( | |
{ name: "AES-GCM", length: 128 }, | |
true, // extractable | |
["encrypt", "decrypt"], | |
); | |
const content = { | |
foo: "bar", | |
}; | |
const encrypted = await crypto.subtle.encrypt( | |
{ name: "AES-GCM", iv: new Uint8Array(12) /* don't reuse key! */ }, | |
key, | |
new TextEncoder().encode(JSON.stringify(content)), | |
); | |
const objectKey = (await crypto.subtle.exportKey("jwk", key)).k; | |
console.log({ objectKey, encrypted }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment