Skip to content

Instantly share code, notes, and snippets.

@NikaBuligini
Last active November 21, 2024 14:51
Show Gist options
  • Save NikaBuligini/5063f64d1975c77f6cd7b4035f4e28b4 to your computer and use it in GitHub Desktop.
Save NikaBuligini/5063f64d1975c77f6cd7b4035f4e28b4 to your computer and use it in GitHub Desktop.
Encryption
// 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"}'
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