File size: 1,807 Bytes
71c519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// A simplified client-side encryption simulation using Web Crypto API
// In a real app, this would handle key exchange (Diffie-Hellman)
export const cryptoUtils = {
  async encrypt(text, keyString) {
    const enc = new TextEncoder();
    const keyData = enc.encode(keyString.padEnd(32, '0')); // Simple padding for demo
    const key = await window.crypto.subtle.importKey(
      "raw",
      keyData,
      { name: "AES-GCM" },
      false,
      ["encrypt"]
    );
    
    const iv = window.crypto.getRandomValues(new Uint8Array(12));
    const encodedText = enc.encode(text);
    
    const encrypted = await window.crypto.subtle.encrypt(
      { name: "AES-GCM", iv: iv },
      key,
      encodedText
    );

    // Combine IV and ciphertext for storage/transmission
    const combined = new Uint8Array(iv.length + encrypted.byteLength);
    combined.set(iv);
    combined.set(new Uint8Array(encrypted), iv.length);
    
    // Return base64 string for easy handling
    return btoa(String.fromCharCode(...combined));
  },

  async decrypt(base64Data, keyString) {
    try {
      const combined = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0));
      const iv = combined.slice(0, 12);
      const data = combined.slice(12);
      
      const enc = new TextEncoder();
      const keyData = enc.encode(keyString.padEnd(32, '0'));
      
      const key = await window.crypto.subtle.importKey(
        "raw",
        keyData,
        { name: "AES-GCM" },
        false,
        ["decrypt"]
      );

      const decrypted = await window.crypto.subtle.decrypt(
        { name: "AES-GCM", iv: iv },
        key,
        data
      );

      const dec = new TextDecoder();
      return dec.decode(decrypted);
    } catch (e) {
      return "⚠️ Decryption Failed: Key Mismatch";
    }
  }
};