Files
ChatApp/packages/shared/src/crypto/keys.ts
T
2026-04-18 23:11:35 +02:00

40 lines
1.3 KiB
TypeScript

import { getCryptoBackend } from './backend.js';
export interface X25519KeyPair {
publicKey: Uint8Array; // 32 bytes
privateKey: Uint8Array; // 32 bytes
}
export async function generateX25519KeyPair(): Promise<X25519KeyPair> {
const backend = getCryptoBackend();
const kp = backend.generateKeyPair();
return { publicKey: kp.publicKey, privateKey: kp.privateKey };
}
// ---- base64 helpers (used to persist private keys client-side) ----------
// Use browser-native btoa/atob. Both are available in Tauri webview and RN
// (Expo polyfills atob/btoa). No external dep needed.
export async function toBase64(bytes: Uint8Array): Promise<string> {
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]!);
}
return btoa(binary);
}
export async function fromBase64(input: string): Promise<Uint8Array> {
const binary = atob(input);
const out = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
out[i] = binary.charCodeAt(i);
}
return out;
}
// Wipe a key best-effort. JS can't truly guarantee zeroization but
// overwriting the buffer removes the value from live references.
export function wipe(bytes: Uint8Array): void {
for (let i = 0; i < bytes.length; i++) bytes[i] = 0;
}