aboutsummaryrefslogtreecommitdiff
path: root/client/src/utils/encryption.js
diff options
context:
space:
mode:
Diffstat (limited to 'client/src/utils/encryption.js')
-rw-r--r--client/src/utils/encryption.js81
1 files changed, 81 insertions, 0 deletions
diff --git a/client/src/utils/encryption.js b/client/src/utils/encryption.js
new file mode 100644
index 0000000..e0e6c33
--- /dev/null
+++ b/client/src/utils/encryption.js
@@ -0,0 +1,81 @@
+async function generateAESKey() {
+ try {
+ const key = await window.crypto.subtle.generateKey(
+ {
+ name: "AES-GCM",
+ length: 256,
+ },
+ true,
+ ["encrypt", "decrypt"],
+ );
+ return key;
+ } catch (error) {
+ console.error("Error generating AES key:", error);
+ }
+}
+
+async function keyToString(key) {
+ try {
+ const exportedKey = await window.crypto.subtle.exportKey("raw", key);
+ const keyString = btoa(String.fromCharCode(...new Uint8Array(exportedKey)));
+ return keyString.replace(/\+/g, "-").replace(/\//g, "_");
+ } catch (error) {
+ console.error("Error converting key to string:", error);
+ }
+}
+
+async function stringToKey(keyString) {
+ try {
+ const originalKeyString = keyString.replace(/-/g, "+").replace(/_/g, "/");
+ const buffer = Uint8Array.from(atob(originalKeyString), (c) =>
+ c.charCodeAt(0),
+ ).buffer;
+
+ const key = await window.crypto.subtle.importKey(
+ "raw",
+ buffer,
+ { name: "AES-GCM", length: 256 },
+ true,
+ ["encrypt", "decrypt"],
+ );
+
+ return key;
+ } catch (error) {
+ console.error("Error converting string to key:", error);
+ }
+}
+
+async function encryptAES(plaintext, key) {
+ try {
+ const iv = window.crypto.getRandomValues(new Uint8Array(12));
+ const encrypted = await window.crypto.subtle.encrypt(
+ {
+ name: "AES-GCM",
+ iv: iv,
+ },
+ key,
+ new TextEncoder().encode(plaintext),
+ );
+ return { encrypted, iv };
+ } catch (error) {
+ console.error("Error encrypting:", error);
+ }
+}
+
+async function decryptAES(encrypted, key, iv) {
+ try {
+ const decrypted = await window.crypto.subtle.decrypt(
+ {
+ name: "AES-GCM",
+ iv: iv,
+ },
+ key,
+ encrypted,
+ );
+ return new TextDecoder().decode(decrypted);
+ } catch (error) {
+ console.error("Error decrypting:", error);
+ }
+}
+
+export { generateAESKey, keyToString, stringToKey, encryptAES, decryptAES };