Spaces:
Runtime error

vibra / fe /src /utils /security.ts
valent-p's picture
chore: update node_modules dependencies and project configuration files
330c3b5
Raw History Blame Contribute Delete
3.92 kB
// ==========================================
// 1. SAFE CRYPTO & SERIALIZATION UTILITIES
// ==========================================
function arrayBufferToBase64(buffer: ArrayBuffer): string {
let binary = "";
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binaryString = window.atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
async function generateECDHKeyPair(): Promise<CryptoKeyPair> {
return await window.crypto.subtle.generateKey(
{ name: "ECDH", namedCurve: "P-256" },
true,
["deriveKey", "deriveBits"]
);
}
async function exportKeyToJWK(key: CryptoKey): Promise<string> {
const jwk = await window.crypto.subtle.exportKey("jwk", key);
return JSON.stringify(jwk);
}
async function importPrivateKey(jwkString: string): Promise<CryptoKey> {
try {
let parsed = JSON.parse(jwkString);
if (typeof parsed === "string") {
parsed = JSON.parse(parsed); // Handle double-stringification
}
return await window.crypto.subtle.importKey(
"jwk",
parsed,
{ name: "ECDH", namedCurve: "P-256" },
false,
["deriveKey"]
);
} catch (err) {
throw new Error("Your local private key is corrupted or invalid. Try logging out and creating a new identity.");
}
}
async function importPublicKey(jwkString: string): Promise<CryptoKey> {
try {
let parsed = JSON.parse(jwkString);
if (typeof parsed === "string") {
parsed = JSON.parse(parsed); // Handle double-stringification
}
return await window.crypto.subtle.importKey(
"jwk",
parsed,
{ name: "ECDH", namedCurve: "P-256" },
true,
[]
);
} catch (err) {
throw new Error("The recipient's E2EE public key is invalid or incompatible.");
}
}
async function deriveSymmetricKey(myPrivateKey: CryptoKey, otherPublicKey: CryptoKey): Promise<CryptoKey> {
return await window.crypto.subtle.deriveKey(
{ name: "ECDH", public: otherPublicKey },
myPrivateKey,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
}
async function encryptMessage(plaintext: string, aesKey: CryptoKey): Promise<{ ciphertext: string; iv: string }> {
const encoder = new TextEncoder();
const data = encoder.encode(plaintext);
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const encryptedBuffer = await window.crypto.subtle.encrypt(
{ name: "AES-GCM", iv: iv },
aesKey,
data
);
return {
ciphertext: arrayBufferToBase64(encryptedBuffer),
iv: arrayBufferToBase64(iv.buffer),
};
}
async function decryptMessage(ciphertextBase64: string, ivBase64: string, aesKey: CryptoKey): Promise<string> {
try {
const ciphertext = base64ToArrayBuffer(ciphertextBase64);
const iv = base64ToArrayBuffer(ivBase64);
const decryptedBuffer = await window.crypto.subtle.decrypt(
{ name: "AES-GCM", iv: new Uint8Array(iv) },
aesKey,
ciphertext
);
const decoder = new TextDecoder();
return decoder.decode(decryptedBuffer);
} catch (error) {
return "[Decryption Error: Key mismatch]";
}
}
export {
arrayBufferToBase64,
base64ToArrayBuffer,
generateECDHKeyPair,
exportKeyToJWK,
importPrivateKey,
importPublicKey,
deriveSymmetricKey,
encryptMessage,
decryptMessage,
};