anycoder-804f2c8b / components /EncryptionHelper.js
Rms666777's picture
Upload components/EncryptionHelper.js with huggingface_hub
71c519f verified
// 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";
}
}
};