@bcts/crypto 1.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.iife.js","names":["nobleSha256","nobleSha512","x25519","secp256k1","secp256k1","SecureRandomNumberGenerator","schnorr","ed25519"],"sources":["../src/error.ts","../src/memzero.ts","../src/hash.ts","../src/symmetric-encryption.ts","../src/public-key-encryption.ts","../src/ecdsa-keys.ts","../src/ecdsa-signing.ts","../src/schnorr-signing.ts","../src/ed25519-signing.ts","../src/scrypt.ts","../src/argon.ts"],"sourcesContent":["// Ported from bc-crypto-rust/src/error.rs\n\n/**\n * AEAD-specific error for authentication failures\n */\nexport class AeadError extends Error {\n constructor(message = \"AEAD authentication failed\") {\n super(message);\n this.name = \"AeadError\";\n }\n}\n\n/**\n * Generic crypto error type\n */\nexport class CryptoError extends Error {\n override readonly cause?: Error | undefined;\n\n constructor(message: string, cause?: Error) {\n super(message);\n this.name = \"CryptoError\";\n this.cause = cause;\n }\n\n /**\n * Create a CryptoError for AEAD authentication failures.\n *\n * @param error - Optional underlying AeadError\n * @returns A CryptoError wrapping the AEAD error\n */\n static aead(error?: AeadError): CryptoError {\n return new CryptoError(\"AEAD error\", error ?? new AeadError());\n }\n\n /**\n * Create a CryptoError for invalid parameter values.\n *\n * @param message - Description of the invalid parameter\n * @returns A CryptoError describing the invalid parameter\n */\n static invalidParameter(message: string): CryptoError {\n return new CryptoError(`Invalid parameter: ${message}`);\n }\n}\n\n/**\n * Result type for crypto operations (using standard Error)\n */\nexport type CryptoResult<T> = T;\n","// Ported from bc-crypto-rust/src/memzero.rs\n\n/**\n * Securely zero out a typed array.\n *\n * **IMPORTANT: This is a best-effort implementation.** Unlike the Rust reference\n * implementation which uses `std::ptr::write_volatile()` for guaranteed volatile\n * writes, JavaScript engines and JIT compilers can still potentially optimize\n * away these zeroing operations. The check at the end helps prevent optimization,\n * but it is not foolproof.\n *\n * For truly sensitive cryptographic operations, consider using the Web Crypto API's\n * `crypto.subtle` with non-extractable keys when possible, as it provides stronger\n * guarantees than what can be achieved with pure JavaScript.\n *\n * This function attempts to prevent the compiler from optimizing away\n * the zeroing operation by using a verification check after the zeroing loop.\n */\nexport function memzero(data: Uint8Array | Uint32Array): void {\n const len = data.length;\n for (let i = 0; i < len; i++) {\n data[i] = 0;\n }\n // Force a side effect to prevent optimization\n if (data.length > 0 && data[0] !== 0) {\n throw new Error(\"memzero failed\");\n }\n}\n\n/**\n * Securely zero out an array of Uint8Arrays.\n */\nexport function memzeroVecVecU8(arrays: Uint8Array[]): void {\n for (const arr of arrays) {\n memzero(arr);\n }\n}\n","// Ported from bc-crypto-rust/src/hash.rs\n\nimport { sha256 as nobleSha256, sha512 as nobleSha512 } from \"@noble/hashes/sha2.js\";\nimport { hmac } from \"@noble/hashes/hmac.js\";\nimport { pbkdf2 } from \"@noble/hashes/pbkdf2.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\n\n// Constants\nexport const CRC32_SIZE = 4;\nexport const SHA256_SIZE = 32;\nexport const SHA512_SIZE = 64;\n\n// CRC-32 lookup table (IEEE polynomial 0xedb88320)\nconst CRC32_TABLE = new Uint32Array(256);\nfor (let i = 0; i < 256; i++) {\n let crc = i;\n for (let j = 0; j < 8; j++) {\n crc = (crc & 1) !== 0 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;\n }\n CRC32_TABLE[i] = crc >>> 0;\n}\n\n/**\n * Calculate CRC-32 checksum\n */\nexport function crc32(data: Uint8Array): number {\n let crc = 0xffffffff;\n for (const byte of data) {\n crc = CRC32_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ 0xffffffff) >>> 0;\n}\n\n/**\n * Calculate CRC-32 checksum and return as a 4-byte big-endian array\n */\nexport function crc32Data(data: Uint8Array): Uint8Array {\n return crc32DataOpt(data, false);\n}\n\n/**\n * Calculate CRC-32 checksum and return as a 4-byte array\n * @param data - Input data\n * @param littleEndian - If true, returns little-endian; otherwise big-endian\n */\nexport function crc32DataOpt(data: Uint8Array, littleEndian: boolean): Uint8Array {\n const checksum = crc32(data);\n const result = new Uint8Array(4);\n const view = new DataView(result.buffer);\n view.setUint32(0, checksum, littleEndian);\n return result;\n}\n\n/**\n * Calculate SHA-256 hash\n */\nexport function sha256(data: Uint8Array): Uint8Array {\n return nobleSha256(data);\n}\n\n/**\n * Calculate double SHA-256 hash (SHA-256 of SHA-256)\n * This is the standard Bitcoin hashing function\n */\nexport function doubleSha256(message: Uint8Array): Uint8Array {\n return sha256(sha256(message));\n}\n\n/**\n * Calculate SHA-512 hash\n */\nexport function sha512(data: Uint8Array): Uint8Array {\n return nobleSha512(data);\n}\n\n/**\n * Calculate HMAC-SHA-256\n */\nexport function hmacSha256(key: Uint8Array, message: Uint8Array): Uint8Array {\n return hmac(nobleSha256, key, message);\n}\n\n/**\n * Calculate HMAC-SHA-512\n */\nexport function hmacSha512(key: Uint8Array, message: Uint8Array): Uint8Array {\n return hmac(nobleSha512, key, message);\n}\n\n/**\n * Derive a key using PBKDF2 with HMAC-SHA-256\n */\nexport function pbkdf2HmacSha256(\n password: Uint8Array,\n salt: Uint8Array,\n iterations: number,\n keyLen: number,\n): Uint8Array {\n return pbkdf2(nobleSha256, password, salt, { c: iterations, dkLen: keyLen });\n}\n\n/**\n * Derive a key using PBKDF2 with HMAC-SHA-512\n */\nexport function pbkdf2HmacSha512(\n password: Uint8Array,\n salt: Uint8Array,\n iterations: number,\n keyLen: number,\n): Uint8Array {\n return pbkdf2(nobleSha512, password, salt, { c: iterations, dkLen: keyLen });\n}\n\n/**\n * Derive a key using HKDF with HMAC-SHA-256\n */\nexport function hkdfHmacSha256(\n keyMaterial: Uint8Array,\n salt: Uint8Array,\n keyLen: number,\n): Uint8Array {\n return hkdf(nobleSha256, keyMaterial, salt, undefined, keyLen);\n}\n\n/**\n * Derive a key using HKDF with HMAC-SHA-512\n */\nexport function hkdfHmacSha512(\n keyMaterial: Uint8Array,\n salt: Uint8Array,\n keyLen: number,\n): Uint8Array {\n return hkdf(nobleSha512, keyMaterial, salt, undefined, keyLen);\n}\n","// Ported from bc-crypto-rust/src/symmetric_encryption.rs\n\nimport { chacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { CryptoError, AeadError } from \"./error.js\";\n\n// Constants\nexport const SYMMETRIC_KEY_SIZE = 32;\nexport const SYMMETRIC_NONCE_SIZE = 12;\nexport const SYMMETRIC_AUTH_SIZE = 16;\n\n/**\n * Encrypt data using ChaCha20-Poly1305 AEAD cipher.\n *\n * **Security Warning**: The nonce MUST be unique for every encryption operation\n * with the same key. Reusing a nonce completely breaks the security of the\n * encryption scheme and can reveal plaintext.\n *\n * @param plaintext - The data to encrypt\n * @param key - 32-byte encryption key\n * @param nonce - 12-byte nonce (MUST be unique per encryption with the same key)\n * @returns Tuple of [ciphertext, authTag] where authTag is 16 bytes\n * @throws {CryptoError} If key is not 32 bytes or nonce is not 12 bytes\n */\nexport function aeadChaCha20Poly1305Encrypt(\n plaintext: Uint8Array,\n key: Uint8Array,\n nonce: Uint8Array,\n): [Uint8Array, Uint8Array] {\n return aeadChaCha20Poly1305EncryptWithAad(plaintext, key, nonce, new Uint8Array(0));\n}\n\n/**\n * Encrypt data using ChaCha20-Poly1305 AEAD cipher with additional authenticated data.\n *\n * **Security Warning**: The nonce MUST be unique for every encryption operation\n * with the same key. Reusing a nonce completely breaks the security of the\n * encryption scheme and can reveal plaintext.\n *\n * @param plaintext - The data to encrypt\n * @param key - 32-byte encryption key\n * @param nonce - 12-byte nonce (MUST be unique per encryption with the same key)\n * @param aad - Additional authenticated data (not encrypted, but integrity-protected)\n * @returns Tuple of [ciphertext, authTag] where authTag is 16 bytes\n * @throws {CryptoError} If key is not 32 bytes or nonce is not 12 bytes\n */\nexport function aeadChaCha20Poly1305EncryptWithAad(\n plaintext: Uint8Array,\n key: Uint8Array,\n nonce: Uint8Array,\n aad: Uint8Array,\n): [Uint8Array, Uint8Array] {\n if (key.length !== SYMMETRIC_KEY_SIZE) {\n throw CryptoError.invalidParameter(`Key must be ${SYMMETRIC_KEY_SIZE} bytes`);\n }\n if (nonce.length !== SYMMETRIC_NONCE_SIZE) {\n throw CryptoError.invalidParameter(`Nonce must be ${SYMMETRIC_NONCE_SIZE} bytes`);\n }\n\n const cipher = chacha20poly1305(key, nonce, aad);\n const sealed = cipher.encrypt(plaintext);\n\n // The sealed output contains ciphertext + 16-byte auth tag\n const ciphertext = sealed.slice(0, sealed.length - SYMMETRIC_AUTH_SIZE);\n const authTag = sealed.slice(sealed.length - SYMMETRIC_AUTH_SIZE);\n\n return [ciphertext, authTag];\n}\n\n/**\n * Decrypt data using ChaCha20-Poly1305 AEAD cipher.\n *\n * @param ciphertext - The encrypted data\n * @param key - 32-byte encryption key (must match key used for encryption)\n * @param nonce - 12-byte nonce (must match nonce used for encryption)\n * @param authTag - 16-byte authentication tag from encryption\n * @returns Decrypted plaintext\n * @throws {CryptoError} If key/nonce/authTag sizes are invalid\n * @throws {CryptoError} If authentication fails (tampered data or wrong key/nonce)\n */\nexport function aeadChaCha20Poly1305Decrypt(\n ciphertext: Uint8Array,\n key: Uint8Array,\n nonce: Uint8Array,\n authTag: Uint8Array,\n): Uint8Array {\n return aeadChaCha20Poly1305DecryptWithAad(ciphertext, key, nonce, new Uint8Array(0), authTag);\n}\n\n/**\n * Decrypt data using ChaCha20-Poly1305 AEAD cipher with additional authenticated data.\n *\n * @param ciphertext - The encrypted data\n * @param key - 32-byte encryption key (must match key used for encryption)\n * @param nonce - 12-byte nonce (must match nonce used for encryption)\n * @param aad - Additional authenticated data (must exactly match AAD used for encryption)\n * @param authTag - 16-byte authentication tag from encryption\n * @returns Decrypted plaintext\n * @throws {CryptoError} If key/nonce/authTag sizes are invalid\n * @throws {CryptoError} If authentication fails (tampered data, wrong key/nonce, or AAD mismatch)\n */\nexport function aeadChaCha20Poly1305DecryptWithAad(\n ciphertext: Uint8Array,\n key: Uint8Array,\n nonce: Uint8Array,\n aad: Uint8Array,\n authTag: Uint8Array,\n): Uint8Array {\n if (key.length !== SYMMETRIC_KEY_SIZE) {\n throw CryptoError.invalidParameter(`Key must be ${SYMMETRIC_KEY_SIZE} bytes`);\n }\n if (nonce.length !== SYMMETRIC_NONCE_SIZE) {\n throw CryptoError.invalidParameter(`Nonce must be ${SYMMETRIC_NONCE_SIZE} bytes`);\n }\n if (authTag.length !== SYMMETRIC_AUTH_SIZE) {\n throw CryptoError.invalidParameter(`Auth tag must be ${SYMMETRIC_AUTH_SIZE} bytes`);\n }\n\n // Combine ciphertext and auth tag for decryption\n const sealed = new Uint8Array(ciphertext.length + authTag.length);\n sealed.set(ciphertext);\n sealed.set(authTag, ciphertext.length);\n\n try {\n const cipher = chacha20poly1305(key, nonce, aad);\n return cipher.decrypt(sealed);\n } catch (error) {\n // Preserve the original error for debugging while wrapping in our error type\n const aeadError = new AeadError(\n `Decryption failed: ${error instanceof Error ? error.message : \"authentication error\"}`,\n );\n throw CryptoError.aead(aeadError);\n }\n}\n","// Ported from bc-crypto-rust/src/public_key_encryption.rs\n\nimport { x25519 } from \"@noble/curves/ed25519.js\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { hkdfHmacSha256 } from \"./hash.js\";\n\n// Constants\nexport const GENERIC_PRIVATE_KEY_SIZE = 32;\nexport const GENERIC_PUBLIC_KEY_SIZE = 32;\nexport const X25519_PRIVATE_KEY_SIZE = 32;\nexport const X25519_PUBLIC_KEY_SIZE = 32;\n\n/**\n * Derive an X25519 agreement private key from key material.\n * Uses HKDF with \"agreement\" as domain separation salt.\n */\nexport function deriveAgreementPrivateKey(keyMaterial: Uint8Array): Uint8Array {\n const salt = new TextEncoder().encode(\"agreement\");\n return hkdfHmacSha256(keyMaterial, salt, X25519_PRIVATE_KEY_SIZE);\n}\n\n/**\n * Derive a signing private key from key material.\n * Uses HKDF with \"signing\" as domain separation salt.\n */\nexport function deriveSigningPrivateKey(keyMaterial: Uint8Array): Uint8Array {\n const salt = new TextEncoder().encode(\"signing\");\n return hkdfHmacSha256(keyMaterial, salt, 32);\n}\n\n/**\n * Generate a new random X25519 private key.\n */\nexport function x25519NewPrivateKeyUsing(rng: RandomNumberGenerator): Uint8Array {\n return rng.randomData(X25519_PRIVATE_KEY_SIZE);\n}\n\n/**\n * Derive an X25519 public key from a private key.\n */\nexport function x25519PublicKeyFromPrivateKey(privateKey: Uint8Array): Uint8Array {\n if (privateKey.length !== X25519_PRIVATE_KEY_SIZE) {\n throw new Error(`Private key must be ${X25519_PRIVATE_KEY_SIZE} bytes`);\n }\n return x25519.getPublicKey(privateKey);\n}\n\n/**\n * Compute a shared secret using X25519 key agreement (ECDH).\n *\n * **Security Note**: The resulting shared secret should be used with a KDF\n * (like HKDF) before using it as an encryption key. Never use the raw\n * shared secret directly for encryption.\n *\n * @param x25519Private - 32-byte X25519 private key\n * @param x25519Public - 32-byte X25519 public key from the other party\n * @returns 32-byte shared secret\n * @throws {Error} If private key is not 32 bytes or public key is not 32 bytes\n */\nexport function x25519SharedKey(x25519Private: Uint8Array, x25519Public: Uint8Array): Uint8Array {\n if (x25519Private.length !== X25519_PRIVATE_KEY_SIZE) {\n throw new Error(`Private key must be ${X25519_PRIVATE_KEY_SIZE} bytes`);\n }\n if (x25519Public.length !== X25519_PUBLIC_KEY_SIZE) {\n throw new Error(`Public key must be ${X25519_PUBLIC_KEY_SIZE} bytes`);\n }\n return x25519.getSharedSecret(x25519Private, x25519Public);\n}\n","// Ported from bc-crypto-rust/src/ecdsa_keys.rs\n\nimport { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { hkdfHmacSha256 } from \"./hash.js\";\n\n// Constants\nexport const ECDSA_PRIVATE_KEY_SIZE = 32;\nexport const ECDSA_PUBLIC_KEY_SIZE = 33; // Compressed\nexport const ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE = 65;\nexport const ECDSA_MESSAGE_HASH_SIZE = 32;\nexport const ECDSA_SIGNATURE_SIZE = 64;\nexport const SCHNORR_PUBLIC_KEY_SIZE = 32; // x-only\n\n/**\n * Generate a new random ECDSA private key using secp256k1.\n *\n * Note: Unlike some implementations, this directly returns the random bytes\n * without validation. The secp256k1 library will handle any edge cases when\n * the key is used.\n */\nexport function ecdsaNewPrivateKeyUsing(rng: RandomNumberGenerator): Uint8Array {\n return rng.randomData(ECDSA_PRIVATE_KEY_SIZE);\n}\n\n/**\n * Derive a compressed ECDSA public key from a private key.\n */\nexport function ecdsaPublicKeyFromPrivateKey(privateKey: Uint8Array): Uint8Array {\n if (privateKey.length !== ECDSA_PRIVATE_KEY_SIZE) {\n throw new Error(`Private key must be ${ECDSA_PRIVATE_KEY_SIZE} bytes`);\n }\n return secp256k1.getPublicKey(privateKey, true); // true = compressed\n}\n\n/**\n * Decompress a compressed public key to uncompressed format.\n */\nexport function ecdsaDecompressPublicKey(compressed: Uint8Array): Uint8Array {\n if (compressed.length !== ECDSA_PUBLIC_KEY_SIZE) {\n throw new Error(`Compressed public key must be ${ECDSA_PUBLIC_KEY_SIZE} bytes`);\n }\n const point = secp256k1.Point.fromBytes(compressed);\n return point.toBytes(false); // false = uncompressed\n}\n\n/**\n * Compress an uncompressed public key.\n */\nexport function ecdsaCompressPublicKey(uncompressed: Uint8Array): Uint8Array {\n if (uncompressed.length !== ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE) {\n throw new Error(`Uncompressed public key must be ${ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE} bytes`);\n }\n const point = secp256k1.Point.fromBytes(uncompressed);\n return point.toBytes(true); // true = compressed\n}\n\n/**\n * Derive an ECDSA private key from key material using HKDF.\n *\n * Note: This directly returns the HKDF output without validation,\n * matching the Rust reference implementation behavior.\n */\nexport function ecdsaDerivePrivateKey(keyMaterial: Uint8Array): Uint8Array {\n const salt = new TextEncoder().encode(\"signing\");\n return hkdfHmacSha256(keyMaterial, salt, ECDSA_PRIVATE_KEY_SIZE);\n}\n\n/**\n * Extract the x-only (Schnorr) public key from a private key.\n * This is used for BIP-340 Schnorr signatures.\n */\nexport function schnorrPublicKeyFromPrivateKey(privateKey: Uint8Array): Uint8Array {\n if (privateKey.length !== ECDSA_PRIVATE_KEY_SIZE) {\n throw new Error(`Private key must be ${ECDSA_PRIVATE_KEY_SIZE} bytes`);\n }\n // Get the full public key and extract just the x-coordinate\n const fullPubKey = secp256k1.getPublicKey(privateKey, false); // uncompressed\n // Skip the 0x04 prefix and take only x-coordinate (first 32 bytes after prefix)\n return fullPubKey.slice(1, 33);\n}\n","// Ported from bc-crypto-rust/src/ecdsa_signing.rs\n\nimport { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { doubleSha256 } from \"./hash.js\";\nimport {\n ECDSA_PRIVATE_KEY_SIZE,\n ECDSA_PUBLIC_KEY_SIZE,\n ECDSA_SIGNATURE_SIZE,\n} from \"./ecdsa-keys.js\";\n\n/**\n * Sign a message using ECDSA with secp256k1.\n *\n * The message is hashed with double SHA-256 before signing (Bitcoin standard).\n *\n * **Security Note**: The private key must be kept secret. ECDSA requires\n * cryptographically secure random nonces internally; this is handled by\n * the underlying library using RFC 6979 deterministic nonces.\n *\n * @param privateKey - 32-byte secp256k1 private key\n * @param message - Message to sign (any length, will be double-SHA256 hashed)\n * @returns 64-byte compact signature (r || s format)\n * @throws {Error} If private key is not 32 bytes\n */\nexport function ecdsaSign(privateKey: Uint8Array, message: Uint8Array): Uint8Array {\n if (privateKey.length !== ECDSA_PRIVATE_KEY_SIZE) {\n throw new Error(`Private key must be ${ECDSA_PRIVATE_KEY_SIZE} bytes`);\n }\n\n const messageHash = doubleSha256(message);\n // prehash: false because we already hashed the message with doubleSha256\n return secp256k1.sign(messageHash, privateKey, { prehash: false });\n}\n\n/**\n * Verify an ECDSA signature with secp256k1.\n *\n * The message is hashed with double SHA-256 before verification (Bitcoin standard).\n *\n * @param publicKey - 33-byte compressed secp256k1 public key\n * @param signature - 64-byte compact signature (r || s format)\n * @param message - Original message that was signed\n * @returns `true` if signature is valid, `false` if signature verification fails\n * @throws {Error} If public key is not 33 bytes or signature is not 64 bytes\n */\nexport function ecdsaVerify(\n publicKey: Uint8Array,\n signature: Uint8Array,\n message: Uint8Array,\n): boolean {\n if (publicKey.length !== ECDSA_PUBLIC_KEY_SIZE) {\n throw new Error(`Public key must be ${ECDSA_PUBLIC_KEY_SIZE} bytes`);\n }\n if (signature.length !== ECDSA_SIGNATURE_SIZE) {\n throw new Error(`Signature must be ${ECDSA_SIGNATURE_SIZE} bytes`);\n }\n\n try {\n const messageHash = doubleSha256(message);\n // prehash: false because we already hashed the message with doubleSha256\n return secp256k1.verify(signature, messageHash, publicKey, { prehash: false });\n } catch {\n return false;\n }\n}\n","// Ported from bc-crypto-rust/src/schnorr_signing.rs\n\nimport { schnorr } from \"@noble/curves/secp256k1.js\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\nimport { ECDSA_PRIVATE_KEY_SIZE, SCHNORR_PUBLIC_KEY_SIZE } from \"./ecdsa-keys.js\";\n\n// Constants\nexport const SCHNORR_SIGNATURE_SIZE = 64;\n\n/**\n * Sign a message using Schnorr signature (BIP-340).\n * Uses secure random auxiliary randomness.\n *\n * @param ecdsaPrivateKey - 32-byte private key\n * @param message - Message to sign (not pre-hashed, per BIP-340)\n * @returns 64-byte Schnorr signature\n */\nexport function schnorrSign(ecdsaPrivateKey: Uint8Array, message: Uint8Array): Uint8Array {\n const rng = new SecureRandomNumberGenerator();\n return schnorrSignUsing(ecdsaPrivateKey, message, rng);\n}\n\n/**\n * Sign a message using Schnorr signature with a custom RNG.\n *\n * @param ecdsaPrivateKey - 32-byte private key\n * @param message - Message to sign\n * @param rng - Random number generator for auxiliary randomness\n * @returns 64-byte Schnorr signature\n */\nexport function schnorrSignUsing(\n ecdsaPrivateKey: Uint8Array,\n message: Uint8Array,\n rng: RandomNumberGenerator,\n): Uint8Array {\n const auxRand = rng.randomData(32);\n return schnorrSignWithAuxRand(ecdsaPrivateKey, message, auxRand);\n}\n\n/**\n * Sign a message using Schnorr signature with specific auxiliary randomness.\n * This is useful for deterministic signing in tests.\n *\n * @param ecdsaPrivateKey - 32-byte private key\n * @param message - Message to sign\n * @param auxRand - 32-byte auxiliary randomness (per BIP-340)\n * @returns 64-byte Schnorr signature\n */\nexport function schnorrSignWithAuxRand(\n ecdsaPrivateKey: Uint8Array,\n message: Uint8Array,\n auxRand: Uint8Array,\n): Uint8Array {\n if (ecdsaPrivateKey.length !== ECDSA_PRIVATE_KEY_SIZE) {\n throw new Error(`Private key must be ${ECDSA_PRIVATE_KEY_SIZE} bytes`);\n }\n if (auxRand.length !== 32) {\n throw new Error(\"Auxiliary randomness must be 32 bytes\");\n }\n\n return schnorr.sign(message, ecdsaPrivateKey, auxRand);\n}\n\n/**\n * Verify a Schnorr signature (BIP-340).\n *\n * @param schnorrPublicKey - 32-byte x-only public key\n * @param signature - 64-byte Schnorr signature\n * @param message - Original message\n * @returns true if signature is valid\n */\nexport function schnorrVerify(\n schnorrPublicKey: Uint8Array,\n signature: Uint8Array,\n message: Uint8Array,\n): boolean {\n if (schnorrPublicKey.length !== SCHNORR_PUBLIC_KEY_SIZE) {\n throw new Error(`Public key must be ${SCHNORR_PUBLIC_KEY_SIZE} bytes`);\n }\n if (signature.length !== SCHNORR_SIGNATURE_SIZE) {\n throw new Error(`Signature must be ${SCHNORR_SIGNATURE_SIZE} bytes`);\n }\n\n try {\n return schnorr.verify(signature, message, schnorrPublicKey);\n } catch {\n return false;\n }\n}\n","// Ported from bc-crypto-rust/src/ed25519_signing.rs\n\nimport { ed25519 } from \"@noble/curves/ed25519.js\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\n\n// Constants\nexport const ED25519_PUBLIC_KEY_SIZE = 32;\nexport const ED25519_PRIVATE_KEY_SIZE = 32;\nexport const ED25519_SIGNATURE_SIZE = 64;\n\n/**\n * Generate a new random Ed25519 private key.\n */\nexport function ed25519NewPrivateKeyUsing(rng: RandomNumberGenerator): Uint8Array {\n return rng.randomData(ED25519_PRIVATE_KEY_SIZE);\n}\n\n/**\n * Derive an Ed25519 public key from a private key.\n */\nexport function ed25519PublicKeyFromPrivateKey(privateKey: Uint8Array): Uint8Array {\n if (privateKey.length !== ED25519_PRIVATE_KEY_SIZE) {\n throw new Error(`Private key must be ${ED25519_PRIVATE_KEY_SIZE} bytes`);\n }\n return ed25519.getPublicKey(privateKey);\n}\n\n/**\n * Sign a message using Ed25519.\n *\n * **Security Note**: The private key must be kept secret. The same private key\n * can safely sign multiple messages.\n *\n * @param privateKey - 32-byte Ed25519 private key\n * @param message - Message to sign (any length)\n * @returns 64-byte Ed25519 signature\n * @throws {Error} If private key is not 32 bytes\n */\nexport function ed25519Sign(privateKey: Uint8Array, message: Uint8Array): Uint8Array {\n if (privateKey.length !== ED25519_PRIVATE_KEY_SIZE) {\n throw new Error(`Private key must be ${ED25519_PRIVATE_KEY_SIZE} bytes`);\n }\n return ed25519.sign(message, privateKey);\n}\n\n/**\n * Verify an Ed25519 signature.\n *\n * @param publicKey - 32-byte Ed25519 public key\n * @param message - Original message that was signed\n * @param signature - 64-byte Ed25519 signature\n * @returns `true` if signature is valid, `false` if signature verification fails\n * @throws {Error} If public key is not 32 bytes or signature is not 64 bytes\n */\nexport function ed25519Verify(\n publicKey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array,\n): boolean {\n if (publicKey.length !== ED25519_PUBLIC_KEY_SIZE) {\n throw new Error(`Public key must be ${ED25519_PUBLIC_KEY_SIZE} bytes`);\n }\n if (signature.length !== ED25519_SIGNATURE_SIZE) {\n throw new Error(`Signature must be ${ED25519_SIGNATURE_SIZE} bytes`);\n }\n\n try {\n return ed25519.verify(signature, message, publicKey);\n } catch {\n return false;\n }\n}\n","// Ported from bc-crypto-rust/src/scrypt.rs\n\nimport { scrypt as nobleScrypt } from \"@noble/hashes/scrypt.js\";\n\n/**\n * Derive a key using Scrypt with recommended parameters.\n * Uses N=2^15 (32768), r=8, p=1 as recommended defaults.\n *\n * @param password - Password or passphrase\n * @param salt - Salt value\n * @param outputLen - Desired output length\n * @returns Derived key\n */\nexport function scrypt(password: Uint8Array, salt: Uint8Array, outputLen: number): Uint8Array {\n return scryptOpt(password, salt, outputLen, 15, 8, 1);\n}\n\n/**\n * Derive a key using Scrypt with custom parameters.\n *\n * @param password - Password or passphrase\n * @param salt - Salt value\n * @param outputLen - Desired output length\n * @param logN - Log2 of the CPU/memory cost parameter N (must be <64)\n * @param r - Block size parameter (must be >0)\n * @param p - Parallelization parameter (must be >0)\n * @returns Derived key\n */\nexport function scryptOpt(\n password: Uint8Array,\n salt: Uint8Array,\n outputLen: number,\n logN: number,\n r: number,\n p: number,\n): Uint8Array {\n if (logN >= 64) {\n throw new Error(\"logN must be <64\");\n }\n if (r === 0) {\n throw new Error(\"r must be >0\");\n }\n if (p === 0) {\n throw new Error(\"p must be >0\");\n }\n\n const N = 1 << logN; // 2^logN\n\n return nobleScrypt(password, salt, { N, r, p, dkLen: outputLen });\n}\n","// Ported from bc-crypto-rust/src/argon.rs\n\nimport { argon2id } from \"@noble/hashes/argon2.js\";\n\n/**\n * Derive a key using Argon2id with default parameters.\n *\n * @param password - Password or passphrase\n * @param salt - Salt value (must be at least 8 bytes)\n * @param outputLen - Desired output length\n * @returns Derived key\n */\nexport function argon2idHash(\n password: Uint8Array,\n salt: Uint8Array,\n outputLen: number,\n): Uint8Array {\n // Use default parameters similar to the Rust implementation\n return argon2idHashOpt(password, salt, outputLen, 3, 65536, 4);\n}\n\n/**\n * Derive a key using Argon2id with custom parameters.\n *\n * @param password - Password or passphrase\n * @param salt - Salt value (must be at least 8 bytes)\n * @param outputLen - Desired output length\n * @param iterations - Number of iterations (t)\n * @param memory - Memory in KiB (m)\n * @param parallelism - Degree of parallelism (p)\n * @returns Derived key\n */\nexport function argon2idHashOpt(\n password: Uint8Array,\n salt: Uint8Array,\n outputLen: number,\n iterations: number,\n memory: number,\n parallelism: number,\n): Uint8Array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,IAAI,MAAM,mBAAmB;AAErC,MAAI,MAAM,EACR,OAAM,IAAI,MAAM,eAAe;AAEjC,MAAI,MAAM,EACR,OAAM,IAAI,MAAM,eAAe;AAKjC,6CAAmB,UAAU,MAAM;GAAE,GAF3B,KAAK;GAEyB;GAAG;GAAG,OAAO;GAAW,CAAC;;;;;;;;;;;;;CCpCnE,SAAgB,aACd,UACA,MACA,WACY;AAEZ,SAAO,gBAAgB,UAAU,MAAM,WAAW,GAAG,OAAO,EAAE;;;;;;;;;;;;;CAchE,SAAgB,gBACd,UACA,MACA,WACA,YACA,QACA,aACY;AACZ,+CAAgB,UAAU,MAAM;GAC9B,GAAG;GACH,GAAG;GACH,GAAG;GACH,OAAO;GACR,CAAC"}
package/dist/index.mjs ADDED
@@ -0,0 +1,594 @@
1
+ import { sha256 as sha256$1, sha512 as sha512$1 } from "@noble/hashes/sha2.js";
2
+ import { hmac } from "@noble/hashes/hmac.js";
3
+ import { pbkdf2 } from "@noble/hashes/pbkdf2.js";
4
+ import { hkdf } from "@noble/hashes/hkdf.js";
5
+ import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
6
+ import { ed25519, x25519 } from "@noble/curves/ed25519.js";
7
+ import { schnorr, secp256k1 } from "@noble/curves/secp256k1.js";
8
+ import { SecureRandomNumberGenerator } from "@bcts/rand";
9
+ import { scrypt as scrypt$1 } from "@noble/hashes/scrypt.js";
10
+ import { argon2id } from "@noble/hashes/argon2.js";
11
+
12
+ //#region src/error.ts
13
+ /**
14
+ * AEAD-specific error for authentication failures
15
+ */
16
+ var AeadError = class extends Error {
17
+ constructor(message = "AEAD authentication failed") {
18
+ super(message);
19
+ this.name = "AeadError";
20
+ }
21
+ };
22
+ /**
23
+ * Generic crypto error type
24
+ */
25
+ var CryptoError = class CryptoError extends Error {
26
+ cause;
27
+ constructor(message, cause) {
28
+ super(message);
29
+ this.name = "CryptoError";
30
+ this.cause = cause;
31
+ }
32
+ /**
33
+ * Create a CryptoError for AEAD authentication failures.
34
+ *
35
+ * @param error - Optional underlying AeadError
36
+ * @returns A CryptoError wrapping the AEAD error
37
+ */
38
+ static aead(error) {
39
+ return new CryptoError("AEAD error", error ?? new AeadError());
40
+ }
41
+ /**
42
+ * Create a CryptoError for invalid parameter values.
43
+ *
44
+ * @param message - Description of the invalid parameter
45
+ * @returns A CryptoError describing the invalid parameter
46
+ */
47
+ static invalidParameter(message) {
48
+ return new CryptoError(`Invalid parameter: ${message}`);
49
+ }
50
+ };
51
+
52
+ //#endregion
53
+ //#region src/memzero.ts
54
+ /**
55
+ * Securely zero out a typed array.
56
+ *
57
+ * **IMPORTANT: This is a best-effort implementation.** Unlike the Rust reference
58
+ * implementation which uses `std::ptr::write_volatile()` for guaranteed volatile
59
+ * writes, JavaScript engines and JIT compilers can still potentially optimize
60
+ * away these zeroing operations. The check at the end helps prevent optimization,
61
+ * but it is not foolproof.
62
+ *
63
+ * For truly sensitive cryptographic operations, consider using the Web Crypto API's
64
+ * `crypto.subtle` with non-extractable keys when possible, as it provides stronger
65
+ * guarantees than what can be achieved with pure JavaScript.
66
+ *
67
+ * This function attempts to prevent the compiler from optimizing away
68
+ * the zeroing operation by using a verification check after the zeroing loop.
69
+ */
70
+ function memzero(data) {
71
+ const len = data.length;
72
+ for (let i = 0; i < len; i++) data[i] = 0;
73
+ if (data.length > 0 && data[0] !== 0) throw new Error("memzero failed");
74
+ }
75
+ /**
76
+ * Securely zero out an array of Uint8Arrays.
77
+ */
78
+ function memzeroVecVecU8(arrays) {
79
+ for (const arr of arrays) memzero(arr);
80
+ }
81
+
82
+ //#endregion
83
+ //#region src/hash.ts
84
+ const CRC32_SIZE = 4;
85
+ const SHA256_SIZE = 32;
86
+ const SHA512_SIZE = 64;
87
+ const CRC32_TABLE = new Uint32Array(256);
88
+ for (let i = 0; i < 256; i++) {
89
+ let crc = i;
90
+ for (let j = 0; j < 8; j++) crc = (crc & 1) !== 0 ? crc >>> 1 ^ 3988292384 : crc >>> 1;
91
+ CRC32_TABLE[i] = crc >>> 0;
92
+ }
93
+ /**
94
+ * Calculate CRC-32 checksum
95
+ */
96
+ function crc32(data) {
97
+ let crc = 4294967295;
98
+ for (const byte of data) crc = CRC32_TABLE[(crc ^ byte) & 255] ^ crc >>> 8;
99
+ return (crc ^ 4294967295) >>> 0;
100
+ }
101
+ /**
102
+ * Calculate CRC-32 checksum and return as a 4-byte big-endian array
103
+ */
104
+ function crc32Data(data) {
105
+ return crc32DataOpt(data, false);
106
+ }
107
+ /**
108
+ * Calculate CRC-32 checksum and return as a 4-byte array
109
+ * @param data - Input data
110
+ * @param littleEndian - If true, returns little-endian; otherwise big-endian
111
+ */
112
+ function crc32DataOpt(data, littleEndian) {
113
+ const checksum = crc32(data);
114
+ const result = new Uint8Array(4);
115
+ new DataView(result.buffer).setUint32(0, checksum, littleEndian);
116
+ return result;
117
+ }
118
+ /**
119
+ * Calculate SHA-256 hash
120
+ */
121
+ function sha256(data) {
122
+ return sha256$1(data);
123
+ }
124
+ /**
125
+ * Calculate double SHA-256 hash (SHA-256 of SHA-256)
126
+ * This is the standard Bitcoin hashing function
127
+ */
128
+ function doubleSha256(message) {
129
+ return sha256(sha256(message));
130
+ }
131
+ /**
132
+ * Calculate SHA-512 hash
133
+ */
134
+ function sha512(data) {
135
+ return sha512$1(data);
136
+ }
137
+ /**
138
+ * Calculate HMAC-SHA-256
139
+ */
140
+ function hmacSha256(key, message) {
141
+ return hmac(sha256$1, key, message);
142
+ }
143
+ /**
144
+ * Calculate HMAC-SHA-512
145
+ */
146
+ function hmacSha512(key, message) {
147
+ return hmac(sha512$1, key, message);
148
+ }
149
+ /**
150
+ * Derive a key using PBKDF2 with HMAC-SHA-256
151
+ */
152
+ function pbkdf2HmacSha256(password, salt, iterations, keyLen) {
153
+ return pbkdf2(sha256$1, password, salt, {
154
+ c: iterations,
155
+ dkLen: keyLen
156
+ });
157
+ }
158
+ /**
159
+ * Derive a key using PBKDF2 with HMAC-SHA-512
160
+ */
161
+ function pbkdf2HmacSha512(password, salt, iterations, keyLen) {
162
+ return pbkdf2(sha512$1, password, salt, {
163
+ c: iterations,
164
+ dkLen: keyLen
165
+ });
166
+ }
167
+ /**
168
+ * Derive a key using HKDF with HMAC-SHA-256
169
+ */
170
+ function hkdfHmacSha256(keyMaterial, salt, keyLen) {
171
+ return hkdf(sha256$1, keyMaterial, salt, void 0, keyLen);
172
+ }
173
+ /**
174
+ * Derive a key using HKDF with HMAC-SHA-512
175
+ */
176
+ function hkdfHmacSha512(keyMaterial, salt, keyLen) {
177
+ return hkdf(sha512$1, keyMaterial, salt, void 0, keyLen);
178
+ }
179
+
180
+ //#endregion
181
+ //#region src/symmetric-encryption.ts
182
+ const SYMMETRIC_KEY_SIZE = 32;
183
+ const SYMMETRIC_NONCE_SIZE = 12;
184
+ const SYMMETRIC_AUTH_SIZE = 16;
185
+ /**
186
+ * Encrypt data using ChaCha20-Poly1305 AEAD cipher.
187
+ *
188
+ * **Security Warning**: The nonce MUST be unique for every encryption operation
189
+ * with the same key. Reusing a nonce completely breaks the security of the
190
+ * encryption scheme and can reveal plaintext.
191
+ *
192
+ * @param plaintext - The data to encrypt
193
+ * @param key - 32-byte encryption key
194
+ * @param nonce - 12-byte nonce (MUST be unique per encryption with the same key)
195
+ * @returns Tuple of [ciphertext, authTag] where authTag is 16 bytes
196
+ * @throws {CryptoError} If key is not 32 bytes or nonce is not 12 bytes
197
+ */
198
+ function aeadChaCha20Poly1305Encrypt(plaintext, key, nonce) {
199
+ return aeadChaCha20Poly1305EncryptWithAad(plaintext, key, nonce, new Uint8Array(0));
200
+ }
201
+ /**
202
+ * Encrypt data using ChaCha20-Poly1305 AEAD cipher with additional authenticated data.
203
+ *
204
+ * **Security Warning**: The nonce MUST be unique for every encryption operation
205
+ * with the same key. Reusing a nonce completely breaks the security of the
206
+ * encryption scheme and can reveal plaintext.
207
+ *
208
+ * @param plaintext - The data to encrypt
209
+ * @param key - 32-byte encryption key
210
+ * @param nonce - 12-byte nonce (MUST be unique per encryption with the same key)
211
+ * @param aad - Additional authenticated data (not encrypted, but integrity-protected)
212
+ * @returns Tuple of [ciphertext, authTag] where authTag is 16 bytes
213
+ * @throws {CryptoError} If key is not 32 bytes or nonce is not 12 bytes
214
+ */
215
+ function aeadChaCha20Poly1305EncryptWithAad(plaintext, key, nonce, aad) {
216
+ if (key.length !== SYMMETRIC_KEY_SIZE) throw CryptoError.invalidParameter(`Key must be ${SYMMETRIC_KEY_SIZE} bytes`);
217
+ if (nonce.length !== SYMMETRIC_NONCE_SIZE) throw CryptoError.invalidParameter(`Nonce must be ${SYMMETRIC_NONCE_SIZE} bytes`);
218
+ const sealed = chacha20poly1305(key, nonce, aad).encrypt(plaintext);
219
+ return [sealed.slice(0, sealed.length - SYMMETRIC_AUTH_SIZE), sealed.slice(sealed.length - SYMMETRIC_AUTH_SIZE)];
220
+ }
221
+ /**
222
+ * Decrypt data using ChaCha20-Poly1305 AEAD cipher.
223
+ *
224
+ * @param ciphertext - The encrypted data
225
+ * @param key - 32-byte encryption key (must match key used for encryption)
226
+ * @param nonce - 12-byte nonce (must match nonce used for encryption)
227
+ * @param authTag - 16-byte authentication tag from encryption
228
+ * @returns Decrypted plaintext
229
+ * @throws {CryptoError} If key/nonce/authTag sizes are invalid
230
+ * @throws {CryptoError} If authentication fails (tampered data or wrong key/nonce)
231
+ */
232
+ function aeadChaCha20Poly1305Decrypt(ciphertext, key, nonce, authTag) {
233
+ return aeadChaCha20Poly1305DecryptWithAad(ciphertext, key, nonce, new Uint8Array(0), authTag);
234
+ }
235
+ /**
236
+ * Decrypt data using ChaCha20-Poly1305 AEAD cipher with additional authenticated data.
237
+ *
238
+ * @param ciphertext - The encrypted data
239
+ * @param key - 32-byte encryption key (must match key used for encryption)
240
+ * @param nonce - 12-byte nonce (must match nonce used for encryption)
241
+ * @param aad - Additional authenticated data (must exactly match AAD used for encryption)
242
+ * @param authTag - 16-byte authentication tag from encryption
243
+ * @returns Decrypted plaintext
244
+ * @throws {CryptoError} If key/nonce/authTag sizes are invalid
245
+ * @throws {CryptoError} If authentication fails (tampered data, wrong key/nonce, or AAD mismatch)
246
+ */
247
+ function aeadChaCha20Poly1305DecryptWithAad(ciphertext, key, nonce, aad, authTag) {
248
+ if (key.length !== SYMMETRIC_KEY_SIZE) throw CryptoError.invalidParameter(`Key must be ${SYMMETRIC_KEY_SIZE} bytes`);
249
+ if (nonce.length !== SYMMETRIC_NONCE_SIZE) throw CryptoError.invalidParameter(`Nonce must be ${SYMMETRIC_NONCE_SIZE} bytes`);
250
+ if (authTag.length !== SYMMETRIC_AUTH_SIZE) throw CryptoError.invalidParameter(`Auth tag must be ${SYMMETRIC_AUTH_SIZE} bytes`);
251
+ const sealed = new Uint8Array(ciphertext.length + authTag.length);
252
+ sealed.set(ciphertext);
253
+ sealed.set(authTag, ciphertext.length);
254
+ try {
255
+ return chacha20poly1305(key, nonce, aad).decrypt(sealed);
256
+ } catch (error) {
257
+ const aeadError = new AeadError(`Decryption failed: ${error instanceof Error ? error.message : "authentication error"}`);
258
+ throw CryptoError.aead(aeadError);
259
+ }
260
+ }
261
+
262
+ //#endregion
263
+ //#region src/public-key-encryption.ts
264
+ const GENERIC_PRIVATE_KEY_SIZE = 32;
265
+ const GENERIC_PUBLIC_KEY_SIZE = 32;
266
+ const X25519_PRIVATE_KEY_SIZE = 32;
267
+ const X25519_PUBLIC_KEY_SIZE = 32;
268
+ /**
269
+ * Derive an X25519 agreement private key from key material.
270
+ * Uses HKDF with "agreement" as domain separation salt.
271
+ */
272
+ function deriveAgreementPrivateKey(keyMaterial) {
273
+ return hkdfHmacSha256(keyMaterial, new TextEncoder().encode("agreement"), X25519_PRIVATE_KEY_SIZE);
274
+ }
275
+ /**
276
+ * Derive a signing private key from key material.
277
+ * Uses HKDF with "signing" as domain separation salt.
278
+ */
279
+ function deriveSigningPrivateKey(keyMaterial) {
280
+ return hkdfHmacSha256(keyMaterial, new TextEncoder().encode("signing"), 32);
281
+ }
282
+ /**
283
+ * Generate a new random X25519 private key.
284
+ */
285
+ function x25519NewPrivateKeyUsing(rng) {
286
+ return rng.randomData(X25519_PRIVATE_KEY_SIZE);
287
+ }
288
+ /**
289
+ * Derive an X25519 public key from a private key.
290
+ */
291
+ function x25519PublicKeyFromPrivateKey(privateKey) {
292
+ if (privateKey.length !== X25519_PRIVATE_KEY_SIZE) throw new Error(`Private key must be ${X25519_PRIVATE_KEY_SIZE} bytes`);
293
+ return x25519.getPublicKey(privateKey);
294
+ }
295
+ /**
296
+ * Compute a shared secret using X25519 key agreement (ECDH).
297
+ *
298
+ * **Security Note**: The resulting shared secret should be used with a KDF
299
+ * (like HKDF) before using it as an encryption key. Never use the raw
300
+ * shared secret directly for encryption.
301
+ *
302
+ * @param x25519Private - 32-byte X25519 private key
303
+ * @param x25519Public - 32-byte X25519 public key from the other party
304
+ * @returns 32-byte shared secret
305
+ * @throws {Error} If private key is not 32 bytes or public key is not 32 bytes
306
+ */
307
+ function x25519SharedKey(x25519Private, x25519Public) {
308
+ if (x25519Private.length !== X25519_PRIVATE_KEY_SIZE) throw new Error(`Private key must be ${X25519_PRIVATE_KEY_SIZE} bytes`);
309
+ if (x25519Public.length !== X25519_PUBLIC_KEY_SIZE) throw new Error(`Public key must be ${X25519_PUBLIC_KEY_SIZE} bytes`);
310
+ return x25519.getSharedSecret(x25519Private, x25519Public);
311
+ }
312
+
313
+ //#endregion
314
+ //#region src/ecdsa-keys.ts
315
+ const ECDSA_PRIVATE_KEY_SIZE = 32;
316
+ const ECDSA_PUBLIC_KEY_SIZE = 33;
317
+ const ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE = 65;
318
+ const ECDSA_MESSAGE_HASH_SIZE = 32;
319
+ const ECDSA_SIGNATURE_SIZE = 64;
320
+ const SCHNORR_PUBLIC_KEY_SIZE = 32;
321
+ /**
322
+ * Generate a new random ECDSA private key using secp256k1.
323
+ *
324
+ * Note: Unlike some implementations, this directly returns the random bytes
325
+ * without validation. The secp256k1 library will handle any edge cases when
326
+ * the key is used.
327
+ */
328
+ function ecdsaNewPrivateKeyUsing(rng) {
329
+ return rng.randomData(ECDSA_PRIVATE_KEY_SIZE);
330
+ }
331
+ /**
332
+ * Derive a compressed ECDSA public key from a private key.
333
+ */
334
+ function ecdsaPublicKeyFromPrivateKey(privateKey) {
335
+ if (privateKey.length !== ECDSA_PRIVATE_KEY_SIZE) throw new Error(`Private key must be ${ECDSA_PRIVATE_KEY_SIZE} bytes`);
336
+ return secp256k1.getPublicKey(privateKey, true);
337
+ }
338
+ /**
339
+ * Decompress a compressed public key to uncompressed format.
340
+ */
341
+ function ecdsaDecompressPublicKey(compressed) {
342
+ if (compressed.length !== ECDSA_PUBLIC_KEY_SIZE) throw new Error(`Compressed public key must be ${ECDSA_PUBLIC_KEY_SIZE} bytes`);
343
+ return secp256k1.Point.fromBytes(compressed).toBytes(false);
344
+ }
345
+ /**
346
+ * Compress an uncompressed public key.
347
+ */
348
+ function ecdsaCompressPublicKey(uncompressed) {
349
+ if (uncompressed.length !== ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE) throw new Error(`Uncompressed public key must be ${ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE} bytes`);
350
+ return secp256k1.Point.fromBytes(uncompressed).toBytes(true);
351
+ }
352
+ /**
353
+ * Derive an ECDSA private key from key material using HKDF.
354
+ *
355
+ * Note: This directly returns the HKDF output without validation,
356
+ * matching the Rust reference implementation behavior.
357
+ */
358
+ function ecdsaDerivePrivateKey(keyMaterial) {
359
+ return hkdfHmacSha256(keyMaterial, new TextEncoder().encode("signing"), ECDSA_PRIVATE_KEY_SIZE);
360
+ }
361
+ /**
362
+ * Extract the x-only (Schnorr) public key from a private key.
363
+ * This is used for BIP-340 Schnorr signatures.
364
+ */
365
+ function schnorrPublicKeyFromPrivateKey(privateKey) {
366
+ if (privateKey.length !== ECDSA_PRIVATE_KEY_SIZE) throw new Error(`Private key must be ${ECDSA_PRIVATE_KEY_SIZE} bytes`);
367
+ return secp256k1.getPublicKey(privateKey, false).slice(1, 33);
368
+ }
369
+
370
+ //#endregion
371
+ //#region src/ecdsa-signing.ts
372
+ /**
373
+ * Sign a message using ECDSA with secp256k1.
374
+ *
375
+ * The message is hashed with double SHA-256 before signing (Bitcoin standard).
376
+ *
377
+ * **Security Note**: The private key must be kept secret. ECDSA requires
378
+ * cryptographically secure random nonces internally; this is handled by
379
+ * the underlying library using RFC 6979 deterministic nonces.
380
+ *
381
+ * @param privateKey - 32-byte secp256k1 private key
382
+ * @param message - Message to sign (any length, will be double-SHA256 hashed)
383
+ * @returns 64-byte compact signature (r || s format)
384
+ * @throws {Error} If private key is not 32 bytes
385
+ */
386
+ function ecdsaSign(privateKey, message) {
387
+ if (privateKey.length !== ECDSA_PRIVATE_KEY_SIZE) throw new Error(`Private key must be ${ECDSA_PRIVATE_KEY_SIZE} bytes`);
388
+ const messageHash = doubleSha256(message);
389
+ return secp256k1.sign(messageHash, privateKey, { prehash: false });
390
+ }
391
+ /**
392
+ * Verify an ECDSA signature with secp256k1.
393
+ *
394
+ * The message is hashed with double SHA-256 before verification (Bitcoin standard).
395
+ *
396
+ * @param publicKey - 33-byte compressed secp256k1 public key
397
+ * @param signature - 64-byte compact signature (r || s format)
398
+ * @param message - Original message that was signed
399
+ * @returns `true` if signature is valid, `false` if signature verification fails
400
+ * @throws {Error} If public key is not 33 bytes or signature is not 64 bytes
401
+ */
402
+ function ecdsaVerify(publicKey, signature, message) {
403
+ if (publicKey.length !== ECDSA_PUBLIC_KEY_SIZE) throw new Error(`Public key must be ${ECDSA_PUBLIC_KEY_SIZE} bytes`);
404
+ if (signature.length !== ECDSA_SIGNATURE_SIZE) throw new Error(`Signature must be ${ECDSA_SIGNATURE_SIZE} bytes`);
405
+ try {
406
+ const messageHash = doubleSha256(message);
407
+ return secp256k1.verify(signature, messageHash, publicKey, { prehash: false });
408
+ } catch {
409
+ return false;
410
+ }
411
+ }
412
+
413
+ //#endregion
414
+ //#region src/schnorr-signing.ts
415
+ const SCHNORR_SIGNATURE_SIZE = 64;
416
+ /**
417
+ * Sign a message using Schnorr signature (BIP-340).
418
+ * Uses secure random auxiliary randomness.
419
+ *
420
+ * @param ecdsaPrivateKey - 32-byte private key
421
+ * @param message - Message to sign (not pre-hashed, per BIP-340)
422
+ * @returns 64-byte Schnorr signature
423
+ */
424
+ function schnorrSign(ecdsaPrivateKey, message) {
425
+ return schnorrSignUsing(ecdsaPrivateKey, message, new SecureRandomNumberGenerator());
426
+ }
427
+ /**
428
+ * Sign a message using Schnorr signature with a custom RNG.
429
+ *
430
+ * @param ecdsaPrivateKey - 32-byte private key
431
+ * @param message - Message to sign
432
+ * @param rng - Random number generator for auxiliary randomness
433
+ * @returns 64-byte Schnorr signature
434
+ */
435
+ function schnorrSignUsing(ecdsaPrivateKey, message, rng) {
436
+ return schnorrSignWithAuxRand(ecdsaPrivateKey, message, rng.randomData(32));
437
+ }
438
+ /**
439
+ * Sign a message using Schnorr signature with specific auxiliary randomness.
440
+ * This is useful for deterministic signing in tests.
441
+ *
442
+ * @param ecdsaPrivateKey - 32-byte private key
443
+ * @param message - Message to sign
444
+ * @param auxRand - 32-byte auxiliary randomness (per BIP-340)
445
+ * @returns 64-byte Schnorr signature
446
+ */
447
+ function schnorrSignWithAuxRand(ecdsaPrivateKey, message, auxRand) {
448
+ if (ecdsaPrivateKey.length !== ECDSA_PRIVATE_KEY_SIZE) throw new Error(`Private key must be ${ECDSA_PRIVATE_KEY_SIZE} bytes`);
449
+ if (auxRand.length !== 32) throw new Error("Auxiliary randomness must be 32 bytes");
450
+ return schnorr.sign(message, ecdsaPrivateKey, auxRand);
451
+ }
452
+ /**
453
+ * Verify a Schnorr signature (BIP-340).
454
+ *
455
+ * @param schnorrPublicKey - 32-byte x-only public key
456
+ * @param signature - 64-byte Schnorr signature
457
+ * @param message - Original message
458
+ * @returns true if signature is valid
459
+ */
460
+ function schnorrVerify(schnorrPublicKey, signature, message) {
461
+ if (schnorrPublicKey.length !== SCHNORR_PUBLIC_KEY_SIZE) throw new Error(`Public key must be ${SCHNORR_PUBLIC_KEY_SIZE} bytes`);
462
+ if (signature.length !== SCHNORR_SIGNATURE_SIZE) throw new Error(`Signature must be ${SCHNORR_SIGNATURE_SIZE} bytes`);
463
+ try {
464
+ return schnorr.verify(signature, message, schnorrPublicKey);
465
+ } catch {
466
+ return false;
467
+ }
468
+ }
469
+
470
+ //#endregion
471
+ //#region src/ed25519-signing.ts
472
+ const ED25519_PUBLIC_KEY_SIZE = 32;
473
+ const ED25519_PRIVATE_KEY_SIZE = 32;
474
+ const ED25519_SIGNATURE_SIZE = 64;
475
+ /**
476
+ * Generate a new random Ed25519 private key.
477
+ */
478
+ function ed25519NewPrivateKeyUsing(rng) {
479
+ return rng.randomData(ED25519_PRIVATE_KEY_SIZE);
480
+ }
481
+ /**
482
+ * Derive an Ed25519 public key from a private key.
483
+ */
484
+ function ed25519PublicKeyFromPrivateKey(privateKey) {
485
+ if (privateKey.length !== ED25519_PRIVATE_KEY_SIZE) throw new Error(`Private key must be ${ED25519_PRIVATE_KEY_SIZE} bytes`);
486
+ return ed25519.getPublicKey(privateKey);
487
+ }
488
+ /**
489
+ * Sign a message using Ed25519.
490
+ *
491
+ * **Security Note**: The private key must be kept secret. The same private key
492
+ * can safely sign multiple messages.
493
+ *
494
+ * @param privateKey - 32-byte Ed25519 private key
495
+ * @param message - Message to sign (any length)
496
+ * @returns 64-byte Ed25519 signature
497
+ * @throws {Error} If private key is not 32 bytes
498
+ */
499
+ function ed25519Sign(privateKey, message) {
500
+ if (privateKey.length !== ED25519_PRIVATE_KEY_SIZE) throw new Error(`Private key must be ${ED25519_PRIVATE_KEY_SIZE} bytes`);
501
+ return ed25519.sign(message, privateKey);
502
+ }
503
+ /**
504
+ * Verify an Ed25519 signature.
505
+ *
506
+ * @param publicKey - 32-byte Ed25519 public key
507
+ * @param message - Original message that was signed
508
+ * @param signature - 64-byte Ed25519 signature
509
+ * @returns `true` if signature is valid, `false` if signature verification fails
510
+ * @throws {Error} If public key is not 32 bytes or signature is not 64 bytes
511
+ */
512
+ function ed25519Verify(publicKey, message, signature) {
513
+ if (publicKey.length !== ED25519_PUBLIC_KEY_SIZE) throw new Error(`Public key must be ${ED25519_PUBLIC_KEY_SIZE} bytes`);
514
+ if (signature.length !== ED25519_SIGNATURE_SIZE) throw new Error(`Signature must be ${ED25519_SIGNATURE_SIZE} bytes`);
515
+ try {
516
+ return ed25519.verify(signature, message, publicKey);
517
+ } catch {
518
+ return false;
519
+ }
520
+ }
521
+
522
+ //#endregion
523
+ //#region src/scrypt.ts
524
+ /**
525
+ * Derive a key using Scrypt with recommended parameters.
526
+ * Uses N=2^15 (32768), r=8, p=1 as recommended defaults.
527
+ *
528
+ * @param password - Password or passphrase
529
+ * @param salt - Salt value
530
+ * @param outputLen - Desired output length
531
+ * @returns Derived key
532
+ */
533
+ function scrypt(password, salt, outputLen) {
534
+ return scryptOpt(password, salt, outputLen, 15, 8, 1);
535
+ }
536
+ /**
537
+ * Derive a key using Scrypt with custom parameters.
538
+ *
539
+ * @param password - Password or passphrase
540
+ * @param salt - Salt value
541
+ * @param outputLen - Desired output length
542
+ * @param logN - Log2 of the CPU/memory cost parameter N (must be <64)
543
+ * @param r - Block size parameter (must be >0)
544
+ * @param p - Parallelization parameter (must be >0)
545
+ * @returns Derived key
546
+ */
547
+ function scryptOpt(password, salt, outputLen, logN, r, p) {
548
+ if (logN >= 64) throw new Error("logN must be <64");
549
+ if (r === 0) throw new Error("r must be >0");
550
+ if (p === 0) throw new Error("p must be >0");
551
+ return scrypt$1(password, salt, {
552
+ N: 1 << logN,
553
+ r,
554
+ p,
555
+ dkLen: outputLen
556
+ });
557
+ }
558
+
559
+ //#endregion
560
+ //#region src/argon.ts
561
+ /**
562
+ * Derive a key using Argon2id with default parameters.
563
+ *
564
+ * @param password - Password or passphrase
565
+ * @param salt - Salt value (must be at least 8 bytes)
566
+ * @param outputLen - Desired output length
567
+ * @returns Derived key
568
+ */
569
+ function argon2idHash(password, salt, outputLen) {
570
+ return argon2idHashOpt(password, salt, outputLen, 3, 65536, 4);
571
+ }
572
+ /**
573
+ * Derive a key using Argon2id with custom parameters.
574
+ *
575
+ * @param password - Password or passphrase
576
+ * @param salt - Salt value (must be at least 8 bytes)
577
+ * @param outputLen - Desired output length
578
+ * @param iterations - Number of iterations (t)
579
+ * @param memory - Memory in KiB (m)
580
+ * @param parallelism - Degree of parallelism (p)
581
+ * @returns Derived key
582
+ */
583
+ function argon2idHashOpt(password, salt, outputLen, iterations, memory, parallelism) {
584
+ return argon2id(password, salt, {
585
+ t: iterations,
586
+ m: memory,
587
+ p: parallelism,
588
+ dkLen: outputLen
589
+ });
590
+ }
591
+
592
+ //#endregion
593
+ export { AeadError, CRC32_SIZE, CryptoError, ECDSA_MESSAGE_HASH_SIZE, ECDSA_PRIVATE_KEY_SIZE, ECDSA_PUBLIC_KEY_SIZE, ECDSA_SIGNATURE_SIZE, ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE, ED25519_PRIVATE_KEY_SIZE, ED25519_PUBLIC_KEY_SIZE, ED25519_SIGNATURE_SIZE, GENERIC_PRIVATE_KEY_SIZE, GENERIC_PUBLIC_KEY_SIZE, SCHNORR_PUBLIC_KEY_SIZE, SCHNORR_SIGNATURE_SIZE, SHA256_SIZE, SHA512_SIZE, SYMMETRIC_AUTH_SIZE, SYMMETRIC_KEY_SIZE, SYMMETRIC_NONCE_SIZE, X25519_PRIVATE_KEY_SIZE, X25519_PUBLIC_KEY_SIZE, aeadChaCha20Poly1305Decrypt, aeadChaCha20Poly1305DecryptWithAad, aeadChaCha20Poly1305Encrypt, aeadChaCha20Poly1305EncryptWithAad, argon2idHash, argon2idHashOpt, crc32, crc32Data, crc32DataOpt, deriveAgreementPrivateKey, deriveSigningPrivateKey, doubleSha256, ecdsaCompressPublicKey, ecdsaDecompressPublicKey, ecdsaDerivePrivateKey, ecdsaNewPrivateKeyUsing, ecdsaPublicKeyFromPrivateKey, ecdsaSign, ecdsaVerify, ed25519NewPrivateKeyUsing, ed25519PublicKeyFromPrivateKey, ed25519Sign, ed25519Verify, hkdfHmacSha256, hkdfHmacSha512, hmacSha256, hmacSha512, memzero, memzeroVecVecU8, pbkdf2HmacSha256, pbkdf2HmacSha512, schnorrPublicKeyFromPrivateKey, schnorrSign, schnorrSignUsing, schnorrSignWithAuxRand, schnorrVerify, scrypt, scryptOpt, sha256, sha512, x25519NewPrivateKeyUsing, x25519PublicKeyFromPrivateKey, x25519SharedKey };
594
+ //# sourceMappingURL=index.mjs.map