import * as secp256k1 from "@noble/secp256k1"; import { hkdf } from "@noble/hashes/hkdf"; import { sha256 } from "@noble/hashes/sha256"; import { randomBytes } from "@noble/hashes/utils"; const PRXVT_PREFIX = "PRXVT::v1::"; const AES_KEY_LENGTH = 32; // 256 bits const NONCE_LENGTH = 12; // 96 bits for GCM const TAG_LENGTH = 16; // 128 bits /** * Derive messaging keypair from a wallet signature. * This ensures the same wallet always produces the same messaging keys. * * The user signs a fixed message, and we use that signature to derive keys. */ export function deriveKeysFromSignature(signature: string): { privateKey: Uint8Array; publicKey: Uint8Array } { // Hash the signature to get a 32-byte private key const sigBytes = hexToBytes(signature); const privateKey = sha256(sigBytes); const publicKey = secp256k1.getPublicKey(privateKey, true); // compressed return { privateKey, publicKey }; } /** * The message to sign for key derivation. * This is a constant - signing this message derives your messaging keys. */ export const KEY_DERIVATION_MESSAGE = "Sign this message to access your Hushkit encrypted messages.\n\nThis signature is used to derive your messaging keys. It does not authorize any transaction."; /** * ECIES encryption using secp256k1 + AES-256-GCM * * Format: PRXVT::v1::[ephemeralPubKey(33)][nonce(12)][tag(16)][ciphertext] */ export async function encrypt( message: string, recipientPubKey: Uint8Array ): Promise { // Generate ephemeral key pair const ephemeralPrivKey = secp256k1.utils.randomPrivateKey(); const ephemeralPubKey = secp256k1.getPublicKey(ephemeralPrivKey, true); // compressed // Compute shared secret using ECDH const sharedPoint = secp256k1.getSharedSecret(ephemeralPrivKey, recipientPubKey); // Derive AES key using HKDF const aesKey = hkdf(sha256, sharedPoint.slice(1), undefined, "hushkit-v1", AES_KEY_LENGTH); // Generate random nonce const nonce = randomBytes(NONCE_LENGTH); // Encrypt using AES-256-GCM (Web Crypto API) const encoder = new TextEncoder(); const plaintext = encoder.encode(message); const cryptoKey = await crypto.subtle.importKey( "raw", new Uint8Array(aesKey) as BufferSource, { name: "AES-GCM" }, false, ["encrypt"] ); const encrypted = await crypto.subtle.encrypt( { name: "AES-GCM", iv: new Uint8Array(nonce) as BufferSource, tagLength: TAG_LENGTH * 8 }, cryptoKey, plaintext ); // AES-GCM appends tag to ciphertext const encryptedArray = new Uint8Array(encrypted); const ciphertext = encryptedArray.slice(0, -TAG_LENGTH); const tag = encryptedArray.slice(-TAG_LENGTH); // Build final message: prefix + ephemeralPubKey + nonce + tag + ciphertext const prefix = encoder.encode(PRXVT_PREFIX); const result = new Uint8Array( prefix.length + ephemeralPubKey.length + nonce.length + tag.length + ciphertext.length ); let offset = 0; result.set(prefix, offset); offset += prefix.length; result.set(ephemeralPubKey, offset); offset += ephemeralPubKey.length; result.set(nonce, offset); offset += nonce.length; result.set(tag, offset); offset += tag.length; result.set(ciphertext, offset); return result; } /** * ECIES decryption */ export async function decrypt( data: Uint8Array, privateKey: Uint8Array ): Promise { const decoder = new TextDecoder(); const prefix = decoder.decode(data.slice(0, PRXVT_PREFIX.length)); if (prefix !== PRXVT_PREFIX) { throw new Error("Invalid message format: missing PRXVT prefix"); } let offset = PRXVT_PREFIX.length; // Extract ephemeral public key (33 bytes compressed) const ephemeralPubKey = data.slice(offset, offset + 33); offset += 33; // Extract nonce const nonce = data.slice(offset, offset + NONCE_LENGTH); offset += NONCE_LENGTH; // Extract tag const tag = data.slice(offset, offset + TAG_LENGTH); offset += TAG_LENGTH; // Extract ciphertext const ciphertext = data.slice(offset); // Compute shared secret const sharedPoint = secp256k1.getSharedSecret(privateKey, ephemeralPubKey); // Derive AES key const aesKey = hkdf(sha256, sharedPoint.slice(1), undefined, "hushkit-v1", AES_KEY_LENGTH); // Decrypt using AES-256-GCM const cryptoKey = await crypto.subtle.importKey( "raw", new Uint8Array(aesKey) as BufferSource, { name: "AES-GCM" }, false, ["decrypt"] ); // Reconstruct ciphertext + tag for Web Crypto const encryptedWithTag = new Uint8Array(ciphertext.length + tag.length); encryptedWithTag.set(ciphertext); encryptedWithTag.set(tag, ciphertext.length); const decrypted = await crypto.subtle.decrypt( { name: "AES-GCM", iv: new Uint8Array(nonce) as BufferSource, tagLength: TAG_LENGTH * 8 }, cryptoKey, encryptedWithTag ); return decoder.decode(decrypted); } /** * Generate a new key pair for messaging * @deprecated Use deriveKeysFromSignature instead for wallet-derived keys */ export function generateKeyPair(): { privateKey: Uint8Array; publicKey: Uint8Array } { const privateKey = secp256k1.utils.randomPrivateKey(); const publicKey = secp256k1.getPublicKey(privateKey, true); // compressed return { privateKey, publicKey }; } /** * Get public key from private key */ export function getPublicKey(privateKey: Uint8Array, compressed = true): Uint8Array { return secp256k1.getPublicKey(privateKey, compressed); } /** * Convert hex string to Uint8Array */ export function hexToBytes(hex: string): Uint8Array { const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex; if (cleanHex.length === 0) return new Uint8Array(0); if (!/^[0-9a-fA-F]+$/.test(cleanHex)) { throw new Error("Invalid hex string: contains non-hex characters"); } if (cleanHex.length % 2 !== 0) { throw new Error(`Invalid hex string: odd length (${cleanHex.length})`); } const bytes = new Uint8Array(cleanHex.length / 2); for (let i = 0; i < bytes.length; i++) { bytes[i] = parseInt(cleanHex.slice(i * 2, i * 2 + 2), 16); } return bytes; } /** * Convert Uint8Array to hex string */ export function bytesToHex(bytes: Uint8Array, prefix = true): string { const hex = Array.from(bytes) .map((b) => b.toString(16).padStart(2, "0")) .join(""); return prefix ? "0x" + hex : hex; } /** * Derive public key from Ethereum private key * Ethereum private keys are the same as secp256k1 private keys */ export function derivePublicKeyFromPrivate(privateKeyHex: string): Uint8Array { const privateKey = hexToBytes(privateKeyHex); return secp256k1.getPublicKey(privateKey, true); } /** * Convert an uncompressed public key (65 bytes) to compressed (33 bytes) */ export function compressPublicKey(uncompressedPubKey: Uint8Array): Uint8Array { if (uncompressedPubKey.length === 33) { return uncompressedPubKey; // Already compressed } if (uncompressedPubKey.length === 65) { // Remove the 0x04 prefix and compress const x = uncompressedPubKey.slice(1, 33); const y = uncompressedPubKey.slice(33, 65); // If y is even, prefix is 0x02, if odd, prefix is 0x03 const prefix = (y[31] & 1) === 0 ? 0x02 : 0x03; const compressed = new Uint8Array(33); compressed[0] = prefix; compressed.set(x, 1); return compressed; } if (uncompressedPubKey.length === 64) { // No prefix, just x and y const x = uncompressedPubKey.slice(0, 32); const y = uncompressedPubKey.slice(32, 64); const prefix = (y[31] & 1) === 0 ? 0x02 : 0x03; const compressed = new Uint8Array(33); compressed[0] = prefix; compressed.set(x, 1); return compressed; } throw new Error(`Invalid public key length: ${uncompressedPubKey.length}`); }