Spaces:
Build error
Build error
Upload components/EncryptionHelper.js with huggingface_hub
Browse files
components/EncryptionHelper.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// A simplified client-side encryption simulation using Web Crypto API
|
| 2 |
+
// In a real app, this would handle key exchange (Diffie-Hellman)
|
| 3 |
+
export const cryptoUtils = {
|
| 4 |
+
async encrypt(text, keyString) {
|
| 5 |
+
const enc = new TextEncoder();
|
| 6 |
+
const keyData = enc.encode(keyString.padEnd(32, '0')); // Simple padding for demo
|
| 7 |
+
const key = await window.crypto.subtle.importKey(
|
| 8 |
+
"raw",
|
| 9 |
+
keyData,
|
| 10 |
+
{ name: "AES-GCM" },
|
| 11 |
+
false,
|
| 12 |
+
["encrypt"]
|
| 13 |
+
);
|
| 14 |
+
|
| 15 |
+
const iv = window.crypto.getRandomValues(new Uint8Array(12));
|
| 16 |
+
const encodedText = enc.encode(text);
|
| 17 |
+
|
| 18 |
+
const encrypted = await window.crypto.subtle.encrypt(
|
| 19 |
+
{ name: "AES-GCM", iv: iv },
|
| 20 |
+
key,
|
| 21 |
+
encodedText
|
| 22 |
+
);
|
| 23 |
+
|
| 24 |
+
// Combine IV and ciphertext for storage/transmission
|
| 25 |
+
const combined = new Uint8Array(iv.length + encrypted.byteLength);
|
| 26 |
+
combined.set(iv);
|
| 27 |
+
combined.set(new Uint8Array(encrypted), iv.length);
|
| 28 |
+
|
| 29 |
+
// Return base64 string for easy handling
|
| 30 |
+
return btoa(String.fromCharCode(...combined));
|
| 31 |
+
},
|
| 32 |
+
|
| 33 |
+
async decrypt(base64Data, keyString) {
|
| 34 |
+
try {
|
| 35 |
+
const combined = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0));
|
| 36 |
+
const iv = combined.slice(0, 12);
|
| 37 |
+
const data = combined.slice(12);
|
| 38 |
+
|
| 39 |
+
const enc = new TextEncoder();
|
| 40 |
+
const keyData = enc.encode(keyString.padEnd(32, '0'));
|
| 41 |
+
|
| 42 |
+
const key = await window.crypto.subtle.importKey(
|
| 43 |
+
"raw",
|
| 44 |
+
keyData,
|
| 45 |
+
{ name: "AES-GCM" },
|
| 46 |
+
false,
|
| 47 |
+
["decrypt"]
|
| 48 |
+
);
|
| 49 |
+
|
| 50 |
+
const decrypted = await window.crypto.subtle.decrypt(
|
| 51 |
+
{ name: "AES-GCM", iv: iv },
|
| 52 |
+
key,
|
| 53 |
+
data
|
| 54 |
+
);
|
| 55 |
+
|
| 56 |
+
const dec = new TextDecoder();
|
| 57 |
+
return dec.decode(decrypted);
|
| 58 |
+
} catch (e) {
|
| 59 |
+
return "⚠️ Decryption Failed: Key Mismatch";
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
};
|