Skip to content

Commit 690daff

Browse files
committed
Add utilities to encrypt text.
1 parent 15004f1 commit 690daff

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/utils/encryptionUtils.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// These functions accept and return Uint8Arrays
2+
3+
export async function encryptAESGCM(plaintext, key) {
4+
const iv = crypto.getRandomValues(new Uint8Array(12));
5+
const algorithm = { name: "AES-GCM", iv: iv };
6+
const keyMaterial = await crypto.subtle.importKey("raw", key, algorithm, false, ["encrypt"]);
7+
const ciphertext = await crypto.subtle.encrypt(algorithm, keyMaterial, plaintext);
8+
9+
return new Uint8Array([...iv, ...new Uint8Array(ciphertext)]);
10+
}
11+
12+
export async function decryptAESGCM(ciphertextArray, key) {
13+
const iv = new Uint8Array(ciphertextArray.slice(0, 12));
14+
const algorithm = { name: "AES-GCM", iv: iv };
15+
const keyMaterial = await crypto.subtle.importKey("raw", key, algorithm, false, ["decrypt"]);
16+
const decrypted = await crypto.subtle.decrypt(algorithm, keyMaterial, new Uint8Array(ciphertextArray.slice(12)));
17+
18+
return decrypted;
19+
}

0 commit comments

Comments
 (0)