From bd7de9f94eb6e681610505eb484e90eb68acd5af Mon Sep 17 00:00:00 2001 From: Kavin <20838718+FireMasterK@users.noreply.github.com> Date: Fri, 3 Feb 2023 18:18:53 +0000 Subject: [PATCH] Add utilities to encrypt text. --- src/utils/encryptionUtils.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/utils/encryptionUtils.js diff --git a/src/utils/encryptionUtils.js b/src/utils/encryptionUtils.js new file mode 100644 index 00000000..20ebd3a5 --- /dev/null +++ b/src/utils/encryptionUtils.js @@ -0,0 +1,19 @@ +// These functions accept and return Uint8Arrays + +export async function encryptAESGCM(plaintext, key) { + const iv = crypto.getRandomValues(new Uint8Array(12)); + const algorithm = { name: "AES-GCM", iv: iv }; + const keyMaterial = await crypto.subtle.importKey("raw", key, algorithm, false, ["encrypt"]); + const ciphertext = await crypto.subtle.encrypt(algorithm, keyMaterial, plaintext); + + return new Uint8Array([...iv, ...new Uint8Array(ciphertext)]); +} + +export async function decryptAESGCM(ciphertextArray, key) { + const iv = new Uint8Array(ciphertextArray.slice(0, 12)); + const algorithm = { name: "AES-GCM", iv: iv }; + const keyMaterial = await crypto.subtle.importKey("raw", key, algorithm, false, ["decrypt"]); + const decrypted = await crypto.subtle.decrypt(algorithm, keyMaterial, new Uint8Array(ciphertextArray.slice(12))); + + return decrypted; +}