@bcts/components 1.0.0-alpha.20 → 1.0.0-alpha.21
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.
- package/LICENSE +2 -1
- package/dist/digest-BJkzk4LG.mjs +3 -0
- package/dist/digest-BzlBpAL2.cjs +3 -0
- package/dist/{digest-DGAZAt7R.mjs → digest-DFW8lGqJ.mjs} +13 -1
- package/dist/digest-DFW8lGqJ.mjs.map +1 -0
- package/dist/{digest-DTBmqDcQ.cjs → digest-DWA5qjpo.cjs} +13 -1
- package/dist/digest-DWA5qjpo.cjs.map +1 -0
- package/dist/index.cjs +210 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +28 -8
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +28 -8
- package/dist/index.d.mts.map +1 -1
- package/dist/index.iife.js +212 -0
- package/dist/index.iife.js.map +1 -1
- package/dist/index.mjs +210 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +14 -25
- package/dist/digest-BJdJcMii.cjs +0 -3
- package/dist/digest-DGAZAt7R.mjs.map +0 -1
- package/dist/digest-DTBmqDcQ.cjs.map +0 -1
- package/dist/digest-yHhOyIQh.mjs +0 -3
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["hexToBytes","bytesToHex","TAG_JSON","CryptoError","bytesToHex","TAG_COMPRESSED","Digest","Digest","SYMMETRIC_NONCE_SIZE","CryptoError","SecureRandomNumberGenerator","hexToBytes","bytesToHex","toBase64","TAG_NONCE","cbor","UR","hexToBytes","SecureRandomNumberGenerator","CryptoError","bytesToHex","toBase64","TAG_SALT","cbor","UR","CryptoError","SecureRandomNumberGenerator","hexToBytes","bytesToHex","toBase64","TAG_SEED","TAG_SEED_V1","CborMap","CborDate","cbor","UR","Digest","CryptoError","CryptoError","SecureRandomNumberGenerator","hexToBytes","bytesToHex","toBase64","TAG_ARID","cbor","UR","CryptoError","bytesToHex","toBase64","TAG_UUID","cbor","UR","CryptoError","Digest","bytesToHex","toBase64","TAG_XID","cbor","UR","CryptoError","toBase64","TAG_URI","UR","X25519_PUBLIC_KEY_SIZE","CryptoError","hexToBytes","bytesToHex","toBase64","TAG_X25519_PUBLIC_KEY","cbor","UR","CryptoError","hexToBytes","bytesToHex","toBase64","cbor","Digest","bytesToHex","TAG_ENCRYPTED","UR","CryptoError","hexToBytes","SecureRandomNumberGenerator","bytesToHex","toBase64","TAG_SYMMETRIC_KEY","cbor","UR","X25519_PRIVATE_KEY_SIZE","CryptoError","SecureRandomNumberGenerator","hexToBytes","bytesToHex","toBase64","TAG_X25519_PRIVATE_KEY","cbor","UR","ED25519_PUBLIC_KEY_SIZE","CryptoError","hexToBytes","bytesToHex","toBase64","ED25519_SIGNATURE_SIZE","ED25519_PRIVATE_KEY_SIZE","CryptoError","hexToBytes","SecureRandomNumberGenerator","bytesToHex","toBase64","bytesToHex","sr25519","SecureRandomNumberGenerator","bytesToHex","sr25519","ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE","CryptoError","hexToBytes","bytesToHex","toBase64","TAG_EC_KEY","TAG_EC_KEY_V1","UR","ECDSA_PUBLIC_KEY_SIZE","CryptoError","hexToBytes","bytesToHex","toBase64","TAG_EC_KEY","TAG_EC_KEY_V1","UR","SCHNORR_PUBLIC_KEY_SIZE","CryptoError","hexToBytes","bytesToHex","toBase64","ECDSA_PRIVATE_KEY_SIZE","CryptoError","SecureRandomNumberGenerator","hexToBytes","bytesToHex","toBase64","TAG_EC_KEY","TAG_EC_KEY_V1","UR","SecureRandomNumberGenerator","ml_dsa44","ml_dsa65","ml_dsa87","bytesToHex","TAG_MLDSA_PUBLIC_KEY","UR","bytesToHex","TAG_MLDSA_SIGNATURE","UR","SecureRandomNumberGenerator","bytesToHex","TAG_MLDSA_PRIVATE_KEY","UR","SCHNORR_SIGNATURE_SIZE","CryptoError","hexToBytes","ECDSA_SIGNATURE_SIZE","ED25519_SIGNATURE_SIZE","bytesToHex","TAG_SIGNATURE","TAG_MLDSA_SIGNATURE","UR","Digest","TAG_SIGNING_PUBLIC_KEY","TAG_MLDSA_PUBLIC_KEY","ED25519_PUBLIC_KEY_SIZE","UR","Digest","sigData","TAG_SIGNING_PRIVATE_KEY","TAG_MLDSA_PRIVATE_KEY","ED25519_PRIVATE_KEY_SIZE","UR","CryptoError","SecureRandomNumberGenerator","ml_kem512","ml_kem768","ml_kem1024","bytesToHex","TAG_MLKEM_CIPHERTEXT","UR","mlkemLevelToScheme","isMlkemScheme","bytesToHex","TAG_X25519_PUBLIC_KEY","TAG_MLKEM_CIPHERTEXT","bytesToHex","TAG_MLKEM_PUBLIC_KEY","UR","mlkemLevelToScheme","isMlkemScheme","bytesToHex","Digest","TAG_X25519_PUBLIC_KEY","TAG_MLKEM_PUBLIC_KEY","UR","SecureRandomNumberGenerator","bytesToHex","TAG_MLKEM_PRIVATE_KEY","UR","SecureRandomNumberGenerator","CryptoError","bytesToHex","Digest","TAG_X25519_PRIVATE_KEY","TAG_MLKEM_PRIVATE_KEY","UR","bytesToHex","TAG_SEALED_MESSAGE","UR","SALT_LEN","CryptoError","CryptoError","TAG_ENCRYPTED_KEY","UR","Digest","TAG_PUBLIC_KEYS","UR","Digest","TAG_PRIVATE_KEYS","UR","SecureRandomNumberGenerator","bytesToHex","TAG_PRIVATE_KEY_BASE","UR","hexToBytes","bytesToHex","TAG_SSKR_SHARE","TAG_SSKR_SHARE_V1"],"sources":["../src/private-key-data-provider.ts","../src/encrypter.ts","../src/json.ts","../src/compressed.ts","../src/hkdf-rng.ts","../src/digest-provider.ts","../src/nonce.ts","../src/salt.ts","../src/seed.ts","../src/reference.ts","../src/id/arid.ts","../src/id/uuid.ts","../src/id/xid.ts","../src/id/uri.ts","../src/x25519/x25519-public-key.ts","../src/symmetric/authentication-tag.ts","../src/symmetric/encrypted-message.ts","../src/symmetric/symmetric-key.ts","../src/x25519/x25519-private-key.ts","../src/ed25519/ed25519-public-key.ts","../src/ed25519/ed25519-private-key.ts","../src/sr25519/sr25519-public-key.ts","../src/sr25519/sr25519-private-key.ts","../src/ec-key/ec-key-base.ts","../src/ec-key/ec-uncompressed-public-key.ts","../src/ec-key/ec-public-key.ts","../src/ec-key/schnorr-public-key.ts","../src/ec-key/ec-private-key.ts","../src/mldsa/mldsa-level.ts","../src/mldsa/mldsa-public-key.ts","../src/mldsa/mldsa-signature.ts","../src/mldsa/mldsa-private-key.ts","../src/signing/signature.ts","../src/signing/signing-public-key.ts","../src/signing/signing-private-key.ts","../src/signing/signature-scheme.ts","../src/mlkem/mlkem-level.ts","../src/mlkem/mlkem-ciphertext.ts","../src/encapsulation/encapsulation-ciphertext.ts","../src/mlkem/mlkem-public-key.ts","../src/encapsulation/encapsulation-public-key.ts","../src/mlkem/mlkem-private-key.ts","../src/encapsulation/encapsulation-private-key.ts","../src/encapsulation/encapsulation-scheme.ts","../src/encapsulation/sealed-message.ts","../src/encrypted-key/hash-type.ts","../src/encrypted-key/key-derivation-method.ts","../src/encrypted-key/hkdf-params.ts","../src/encrypted-key/pbkdf2-params.ts","../src/encrypted-key/scrypt-params.ts","../src/encrypted-key/argon2id-params.ts","../src/encrypted-key/ssh-agent-params.ts","../src/encrypted-key/key-derivation-params.ts","../src/encrypted-key/encrypted-key.ts","../src/public-keys.ts","../src/private-keys.ts","../src/private-key-base.ts","../src/sskr.ts"],"sourcesContent":["/**\n * A trait for types that can provide unique data for cryptographic key derivation.\n *\n * Ported from bc-components-rust/src/private_key_data_provider.rs\n *\n * Types implementing `PrivateKeyDataProvider` can be used as seed material for\n * cryptographic key derivation. The provided data should be sufficiently\n * random and unpredictable to ensure the security of the derived keys.\n *\n * This trait is particularly useful for:\n * - Deterministic key generation systems\n * - Key recovery mechanisms\n * - Key derivation hierarchies\n * - Hierarchical deterministic wallet implementations\n *\n * # Security Considerations\n *\n * Implementers of this trait should ensure that:\n * - The data they provide has sufficient entropy\n * - The data is properly protected in memory\n * - Any serialization or storage is done securely\n * - Appropriate zeroization occurs when data is no longer needed\n */\n\n/**\n * Interface for types that can provide unique data for cryptographic key derivation.\n *\n * The provided data should be sufficiently random and have enough entropy\n * to serve as the basis for secure cryptographic key derivation.\n */\nexport interface PrivateKeyDataProvider {\n /**\n * Returns unique data from which cryptographic keys can be derived.\n *\n * The returned data should be sufficiently random and have enough entropy\n * to serve as the basis for secure cryptographic key derivation.\n *\n * @returns A Uint8Array containing the private key data.\n */\n privateKeyData(): Uint8Array;\n}\n\n/**\n * Type guard to check if an object implements PrivateKeyDataProvider\n */\nexport function isPrivateKeyDataProvider(obj: unknown): obj is PrivateKeyDataProvider {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"privateKeyData\" in obj &&\n typeof (obj as PrivateKeyDataProvider).privateKeyData === \"function\"\n );\n}\n","/**\n * Encrypter and Decrypter interfaces for public key encryption/decryption.\n *\n * Ported from bc-components-rust/src/encrypter.rs\n *\n * The `Encrypter` interface defines an interface for encapsulating a shared secret\n * using a public key. This is a key part of hybrid encryption schemes, where a\n * shared symmetric key is encapsulated with a public key, and the recipient\n * uses their private key to recover the symmetric key.\n *\n * The `Decrypter` interface defines an interface for decapsulating (recovering) a\n * shared secret using a private key. This is the counterpart to the\n * `Encrypter` interface and is used by the recipient of encapsulated messages.\n */\n\nimport type { EncapsulationCiphertext } from \"./encapsulation/encapsulation-ciphertext.js\";\nimport type { EncapsulationPrivateKey } from \"./encapsulation/encapsulation-private-key.js\";\nimport type { EncapsulationPublicKey } from \"./encapsulation/encapsulation-public-key.js\";\nimport type { SymmetricKey } from \"./symmetric/symmetric-key.js\";\n\n/**\n * A trait for types that can encapsulate shared secrets for public key encryption.\n *\n * The `Encrypter` interface defines an interface for encapsulating a shared secret\n * using a public key. This is a key part of hybrid encryption schemes, where a\n * shared symmetric key is encapsulated with a public key, and the recipient\n * uses their private key to recover the symmetric key.\n *\n * Types implementing this interface provide the ability to:\n * 1. Access their encapsulation public key\n * 2. Generate and encapsulate new shared secrets\n *\n * This interface is typically implemented by:\n * - Encapsulation public keys\n * - Higher-level types that contain or can generate encapsulation public keys\n *\n * @example\n * ```typescript\n * import { EncapsulationScheme, createEncapsulationKeypair } from '@bcts/components';\n *\n * // Generate a recipient keypair\n * const [recipientPrivateKey, recipientPublicKey] = createEncapsulationKeypair(EncapsulationScheme.X25519);\n *\n * // Encapsulate a new shared secret\n * const [sharedSecret, ciphertext] = recipientPublicKey.encapsulateNewSharedSecret();\n * ```\n */\nexport interface Encrypter {\n /**\n * Returns the encapsulation public key for this encrypter.\n *\n * @returns The encapsulation public key that should be used for encapsulation.\n */\n encapsulationPublicKey(): EncapsulationPublicKey;\n\n /**\n * Encapsulates a new shared secret for the recipient.\n *\n * This method generates a new shared secret and encapsulates it using\n * the encapsulation public key from this encrypter.\n *\n * @returns A tuple containing:\n * - The generated shared secret as a `SymmetricKey`\n * - The encapsulation ciphertext that can be sent to the recipient\n */\n encapsulateNewSharedSecret(): [SymmetricKey, EncapsulationCiphertext];\n}\n\n/**\n * A trait for types that can decapsulate shared secrets for public key decryption.\n *\n * The `Decrypter` interface defines an interface for decapsulating (recovering) a\n * shared secret using a private key. This is the counterpart to the\n * `Encrypter` interface and is used by the recipient of encapsulated messages.\n *\n * Types implementing this interface provide the ability to:\n * 1. Access their encapsulation private key\n * 2. Decapsulate shared secrets from ciphertexts\n *\n * This interface is typically implemented by:\n * - Encapsulation private keys\n * - Higher-level types that contain or can access encapsulation private keys\n *\n * @example\n * ```typescript\n * import { EncapsulationScheme, createEncapsulationKeypair } from '@bcts/components';\n *\n * // Generate a keypair\n * const [privateKey, publicKey] = createEncapsulationKeypair(EncapsulationScheme.X25519);\n *\n * // Encapsulate a new shared secret\n * const [originalSecret, ciphertext] = publicKey.encapsulateNewSharedSecret();\n *\n * // Decapsulate the shared secret\n * const recoveredSecret = privateKey.decapsulateSharedSecret(ciphertext);\n *\n * // The original and recovered secrets should match\n * ```\n */\nexport interface Decrypter {\n /**\n * Returns the encapsulation private key for this decrypter.\n *\n * @returns The encapsulation private key that should be used for decapsulation.\n */\n encapsulationPrivateKey(): EncapsulationPrivateKey;\n\n /**\n * Decapsulates a shared secret from a ciphertext.\n *\n * This method recovers the shared secret that was encapsulated in the\n * given ciphertext, using the private key from this decrypter.\n *\n * @param ciphertext - The encapsulation ciphertext containing the encapsulated shared secret\n * @returns The decapsulated `SymmetricKey`\n * @throws Error if the ciphertext type doesn't match the private key type or if decapsulation fails\n */\n decapsulateSharedSecret(ciphertext: EncapsulationCiphertext): SymmetricKey;\n}\n\n/**\n * Type guard to check if an object implements the Encrypter interface.\n */\nexport function isEncrypter(obj: unknown): obj is Encrypter {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"encapsulationPublicKey\" in obj &&\n typeof (obj as Encrypter).encapsulationPublicKey === \"function\" &&\n \"encapsulateNewSharedSecret\" in obj &&\n typeof (obj as Encrypter).encapsulateNewSharedSecret === \"function\"\n );\n}\n\n/**\n * Type guard to check if an object implements the Decrypter interface.\n */\nexport function isDecrypter(obj: unknown): obj is Decrypter {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"encapsulationPrivateKey\" in obj &&\n typeof (obj as Decrypter).encapsulationPrivateKey === \"function\" &&\n \"decapsulateSharedSecret\" in obj &&\n typeof (obj as Decrypter).decapsulateSharedSecret === \"function\"\n );\n}\n","/**\n * A CBOR-tagged container for UTF-8 JSON text.\n *\n * Ported from bc-components-rust/src/json.rs\n *\n * The `JSON` type wraps UTF-8 JSON text as a CBOR byte string with tag 262.\n * This allows JSON data to be embedded within CBOR structures while\n * maintaining type information through the tag.\n *\n * This implementation does not validate that the contained data is well-formed\n * JSON. It simply provides a type-safe wrapper around byte data that is\n * intended to contain JSON text.\n *\n * # CBOR Serialization\n *\n * `JSON` implements the CBOR tagged encoding interfaces, which means it can be\n * serialized to and deserialized from CBOR with tag 262 (`TAG_JSON`).\n *\n * @example\n * ```typescript\n * import { JSON } from '@bcts/components';\n *\n * // Create JSON from a string\n * const json = JSON.fromString('{\"key\": \"value\"}');\n * console.log(json.asStr()); // {\"key\": \"value\"}\n *\n * // Create JSON from bytes\n * const json2 = JSON.fromData(new TextEncoder().encode('[1, 2, 3]'));\n * console.log(json2.len()); // 9\n * ```\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { JSON as TAG_JSON } from \"@bcts/tags\";\nimport { bytesToHex, hexToBytes } from \"./utils.js\";\n\n/**\n * A CBOR-tagged container for UTF-8 JSON text.\n *\n * Wraps UTF-8 JSON text as a CBOR byte string with tag 262.\n * This allows JSON data to be embedded within CBOR structures while\n * maintaining type information through the tag.\n */\nexport class JSON implements CborTaggedEncodable, CborTaggedDecodable<JSON> {\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new JSON instance from byte data.\n */\n static fromData(data: Uint8Array): JSON {\n return new JSON(data);\n }\n\n /**\n * Create a new JSON instance from a string.\n */\n static fromString(s: string): JSON {\n const encoder = new TextEncoder();\n return new JSON(encoder.encode(s));\n }\n\n /**\n * Create a new JSON instance from a hexadecimal string.\n */\n static fromHex(hex: string): JSON {\n return new JSON(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Return the length of the JSON data in bytes.\n */\n len(): number {\n return this._data.length;\n }\n\n /**\n * Return true if the JSON data is empty.\n */\n isEmpty(): boolean {\n return this._data.length === 0;\n }\n\n /**\n * Return the data as a byte slice.\n */\n asBytes(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Return the data as a UTF-8 string slice.\n *\n * @throws Error if the data is not valid UTF-8.\n */\n asStr(): string {\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n return decoder.decode(this._data);\n }\n\n /**\n * Return the data as a hexadecimal string.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Return a copy of the underlying data.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Compare with another JSON.\n */\n equals(other: JSON): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `JSON(${this.asStr()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with JSON.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_JSON.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a JSON by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): JSON {\n const data = expectBytes(cborValue);\n return JSON.fromData(data);\n }\n\n /**\n * Creates a JSON by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): JSON {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): JSON {\n const instance = JSON.fromString(\"\");\n return instance.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): JSON {\n const cborValue = decodeCbor(data);\n return JSON.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): JSON {\n const cborValue = decodeCbor(data);\n const instance = JSON.fromString(\"\");\n return instance.fromUntaggedCbor(cborValue);\n }\n}\n","/**\n * A compressed binary object with integrity verification.\n *\n * Ported from bc-components-rust/src/compressed.rs\n *\n * `Compressed` provides a way to efficiently store and transmit binary data\n * using the DEFLATE compression algorithm. It includes built-in integrity\n * verification through a CRC32 checksum and optional cryptographic digest.\n *\n * The compression is implemented using the raw DEFLATE format as described in\n * [IETF RFC 1951](https://www.ietf.org/rfc/rfc1951.txt).\n *\n * Features:\n * - Automatic compression with configurable compression level\n * - Integrity verification via CRC32 checksum\n * - Optional cryptographic digest for content identification\n * - Smart behavior for small data (stores decompressed if compression would\n * increase size)\n * - CBOR serialization/deserialization support\n *\n * @example\n * ```typescript\n * import { Compressed } from '@bcts/components';\n *\n * // Compress a string\n * const data = new TextEncoder().encode(\n * \"This is a longer string that should compress well with repeated patterns.\"\n * );\n * const compressed = Compressed.fromDecompressedData(data);\n *\n * // The compressed size should be smaller than the original\n * console.log(compressed.compressionRatio()); // < 1.0\n *\n * // We can recover the original data\n * const decompressed = compressed.decompress();\n * ```\n */\n\nimport { deflate, inflate } from \"pako\";\nimport { crc32 } from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborInput,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n expectArray,\n expectInteger,\n expectBytes,\n} from \"@bcts/dcbor\";\nimport { COMPRESSED as TAG_COMPRESSED } from \"@bcts/tags\";\nimport { Digest } from \"./digest.js\";\nimport type { DigestProvider } from \"./digest-provider.js\";\nimport { CryptoError } from \"./error.js\";\nimport { bytesToHex } from \"./utils.js\";\n\n/**\n * A compressed binary object with integrity verification.\n *\n * Uses DEFLATE compression with CRC32 checksums for integrity verification.\n * Optionally includes a cryptographic digest for content identification.\n */\nexport class Compressed\n implements CborTaggedEncodable, CborTaggedDecodable<Compressed>, DigestProvider\n{\n /** CRC32 checksum of the decompressed data for integrity verification */\n private readonly _checksum: number;\n /** Size of the original decompressed data in bytes */\n private readonly _decompressedSize: number;\n /** The compressed data (or original data if compression is ineffective) */\n private readonly _compressedData: Uint8Array;\n /** Optional cryptographic digest of the content */\n private readonly _digest: Digest | undefined;\n\n private constructor(\n checksum: number,\n decompressedSize: number,\n compressedData: Uint8Array,\n digest?: Digest,\n ) {\n if (compressedData.length > decompressedSize) {\n throw CryptoError.cryptoOperation(\"compressed data is larger than decompressed size\");\n }\n this._checksum = checksum;\n this._decompressedSize = decompressedSize;\n this._compressedData = new Uint8Array(compressedData);\n this._digest = digest;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Creates a new `Compressed` object with the specified parameters.\n *\n * This is a low-level constructor that allows direct creation of a\n * `Compressed` object without performing compression. It's primarily\n * intended for deserialization or when working with pre-compressed data.\n *\n * @param checksum - CRC32 checksum of the decompressed data\n * @param decompressedSize - Size of the original decompressed data in bytes\n * @param compressedData - The compressed data bytes\n * @param digest - Optional cryptographic digest of the content\n * @returns A new `Compressed` object\n * @throws CryptoError if the compressed data is larger than the decompressed size\n */\n static new(\n checksum: number,\n decompressedSize: number,\n compressedData: Uint8Array,\n digest?: Digest,\n ): Compressed {\n return new Compressed(checksum, decompressedSize, compressedData, digest);\n }\n\n /**\n * Creates a new `Compressed` object by compressing the provided data.\n *\n * This is the primary method for creating compressed data. It automatically\n * handles compression using the DEFLATE algorithm with compression level 6.\n *\n * If the compressed data would be larger than the original data (which can\n * happen with small or already compressed inputs), the original data is\n * stored instead.\n *\n * @param decompressedData - The original data to compress\n * @param digest - Optional cryptographic digest of the content\n * @returns A new `Compressed` object containing the compressed (or original) data\n */\n static fromDecompressedData(decompressedData: Uint8Array, digest?: Digest): Compressed {\n // Use raw DEFLATE compression (level 6 is default)\n const compressedData = deflate(decompressedData, { level: 6 });\n const checksum = crc32(decompressedData);\n const decompressedSize = decompressedData.length;\n const compressedSize = compressedData.length;\n\n // If compression didn't help, store original data\n if (compressedSize !== 0 && compressedSize < decompressedSize) {\n return new Compressed(checksum, decompressedSize, compressedData, digest);\n } else {\n return new Compressed(checksum, decompressedSize, new Uint8Array(decompressedData), digest);\n }\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Decompresses and returns the original decompressed data.\n *\n * This method performs the reverse of the compression process, restoring\n * the original data. It also verifies the integrity of the data using the\n * stored checksum.\n *\n * @returns The decompressed data\n * @throws CryptoError if the compressed data is corrupt or checksum doesn't match\n */\n decompress(): Uint8Array {\n const compressedSize = this._compressedData.length;\n\n // If data wasn't actually compressed (sizes equal), return as-is\n if (compressedSize >= this._decompressedSize) {\n return new Uint8Array(this._compressedData);\n }\n\n try {\n const decompressedData = inflate(this._compressedData);\n\n // Verify checksum\n if (crc32(decompressedData) !== this._checksum) {\n throw CryptoError.cryptoOperation(\"compressed data checksum mismatch\");\n }\n\n return decompressedData;\n } catch (e) {\n if (e instanceof CryptoError) throw e;\n throw CryptoError.cryptoOperation(\"corrupt compressed data\");\n }\n }\n\n /**\n * Returns the size of the compressed data in bytes.\n */\n compressedSize(): number {\n return this._compressedData.length;\n }\n\n /**\n * Returns the size of the decompressed data in bytes.\n */\n decompressedSize(): number {\n return this._decompressedSize;\n }\n\n /**\n * Returns the CRC32 checksum of the decompressed data.\n */\n checksum(): number {\n return this._checksum;\n }\n\n /**\n * Returns the compression ratio of the data.\n *\n * The compression ratio is calculated as (compressed size) / (decompressed size),\n * so lower values indicate better compression.\n *\n * @returns A floating-point value representing the compression ratio.\n * - Values less than 1.0 indicate effective compression\n * - Values equal to 1.0 indicate no compression was applied\n * - Values of NaN can occur if the decompressed size is zero\n */\n compressionRatio(): number {\n return this._compressedData.length / this._decompressedSize;\n }\n\n /**\n * Returns the digest of the compressed data, if available.\n *\n * @returns The `Digest` associated with this compressed data, or undefined if none.\n */\n digestOpt(): Digest | undefined {\n return this._digest;\n }\n\n /**\n * Returns whether this compressed data has an associated digest.\n */\n hasDigest(): boolean {\n return this._digest !== undefined;\n }\n\n // ============================================================================\n // DigestProvider implementation\n // ============================================================================\n\n /**\n * Returns the cryptographic digest associated with this compressed data.\n *\n * @returns A `Digest`\n * @throws Error if there is no digest associated with this compressed data\n */\n digest(): Digest {\n if (this._digest === undefined) {\n throw new Error(\"No digest associated with this compressed data\");\n }\n return this._digest;\n }\n\n // ============================================================================\n // Comparison and String representation\n // ============================================================================\n\n /**\n * Compare with another Compressed.\n */\n equals(other: Compressed): boolean {\n if (this._checksum !== other._checksum) return false;\n if (this._decompressedSize !== other._decompressedSize) return false;\n if (this._compressedData.length !== other._compressedData.length) return false;\n for (let i = 0; i < this._compressedData.length; i++) {\n if (this._compressedData[i] !== other._compressedData[i]) return false;\n }\n // Don't compare digests for equality\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n const checksumHex = bytesToHex(\n new Uint8Array([\n (this._checksum >>> 24) & 0xff,\n (this._checksum >>> 16) & 0xff,\n (this._checksum >>> 8) & 0xff,\n this._checksum & 0xff,\n ]),\n );\n const digestStr = this._digest?.shortDescription() ?? \"None\";\n return `Compressed(checksum: ${checksumHex}, size: ${this.compressedSize()}/${this._decompressedSize}, ratio: ${this.compressionRatio().toFixed(2)}, digest: ${digestStr})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with Compressed.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_COMPRESSED.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as an array).\n *\n * Format:\n * ```\n * [\n * checksum: uint,\n * decompressed_size: uint,\n * compressed_data: bytes,\n * digest?: Digest // Optional\n * ]\n * ```\n */\n untaggedCbor(): Cbor {\n const elements: CborInput[] = [\n this._checksum >>> 0, // Ensure unsigned 32-bit\n this._decompressedSize,\n toByteString(this._compressedData),\n ];\n if (this._digest !== undefined) {\n elements.push(this._digest.taggedCbor());\n }\n return cbor(elements);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a Compressed by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): Compressed {\n const elements = expectArray(cborValue);\n if (elements.length < 3 || elements.length > 4) {\n throw CryptoError.invalidData(\"invalid number of elements in compressed\");\n }\n\n const checksum = expectInteger(elements[0]);\n const decompressedSize = expectInteger(elements[1]);\n const compressedData = expectBytes(elements[2]);\n\n let digest: Digest | undefined;\n if (elements.length === 4) {\n digest = Digest.fromTaggedCbor(elements[3]);\n }\n\n return Compressed.new(Number(checksum), Number(decompressedSize), compressedData, digest);\n }\n\n /**\n * Creates a Compressed by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): Compressed {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): Compressed {\n const instance = Compressed.fromDecompressedData(new Uint8Array(0));\n return instance.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): Compressed {\n const cborValue = decodeCbor(data);\n return Compressed.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): Compressed {\n const cborValue = decodeCbor(data);\n const instance = Compressed.fromDecompressedData(new Uint8Array(0));\n return instance.fromUntaggedCbor(cborValue);\n }\n}\n","/**\n * A deterministic random number generator based on HKDF-HMAC-SHA256.\n *\n * Ported from bc-components-rust/src/hkdf_rng.rs\n *\n * `HKDFRng` uses the HMAC-based Key Derivation Function (HKDF) to generate\n * deterministic random numbers from a combination of key material and salt. It\n * serves as a key-stretching mechanism that can produce an arbitrary amount of\n * random-looking bytes from a single seed.\n *\n * Since it produces deterministic output based on the same inputs, it's useful\n * for situations where repeatable randomness is required, such as in testing\n * or when deterministically deriving keys from a master seed.\n *\n * Security considerations:\n * - The security of the generator depends on the entropy and secrecy of the\n * key material\n * - The same key material and salt will always produce the same sequence\n * - Use a secure random seed for cryptographic applications\n * - Never reuse the same HKDFRng instance for different purposes\n *\n * The implementation automatically handles buffer management, fetching new\n * data using HKDF as needed with an incrementing counter to ensure unique\n * output for each request.\n *\n * @example\n * ```typescript\n * import { HKDFRng } from '@bcts/components';\n *\n * // Create an HKDF-based RNG\n * const rng = HKDFRng.new(new TextEncoder().encode(\"my secure seed\"), \"wallet-derivation\");\n *\n * // Generate two u32 values\n * const random1 = rng.nextU32();\n * const random2 = rng.nextU32();\n *\n * // The same seed and salt will always produce the same sequence\n * const rng2 = HKDFRng.new(new TextEncoder().encode(\"my secure seed\"), \"wallet-derivation\");\n * console.log(random1 === rng2.nextU32()); // true\n * console.log(random2 === rng2.nextU32()); // true\n * ```\n */\n\nimport { hkdfHmacSha256 } from \"@bcts/crypto\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\n\nconst DEFAULT_PAGE_LENGTH = 32;\n\n/**\n * A deterministic random number generator based on HKDF-HMAC-SHA256.\n *\n * Implements the RandomNumberGenerator interface from @bcts/rand.\n */\nexport class HKDFRng implements RandomNumberGenerator {\n /** Internal buffer of generated bytes */\n private _buffer: Uint8Array;\n /** Current position in the buffer */\n private _position: number;\n /** Source key material (seed) */\n private readonly _keyMaterial: Uint8Array;\n /** Salt value to combine with the key material */\n private readonly _salt: string;\n /** Length of each \"page\" of generated data */\n private readonly _pageLength: number;\n /** Current page index */\n private _pageIndex: number;\n\n private constructor(keyMaterial: Uint8Array, salt: string, pageLength: number) {\n this._buffer = new Uint8Array(0);\n this._position = 0;\n this._keyMaterial = new Uint8Array(keyMaterial);\n this._salt = salt;\n this._pageLength = pageLength;\n this._pageIndex = 0;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Creates a new `HKDFRng` with a custom page length.\n *\n * @param keyMaterial - The seed material to derive random numbers from\n * @param salt - A salt value to mix with the key material\n * @param pageLength - The number of bytes to generate in each HKDF call\n * @returns A new `HKDFRng` instance configured with the specified parameters\n */\n static newWithPageLength(keyMaterial: Uint8Array, salt: string, pageLength: number): HKDFRng {\n return new HKDFRng(keyMaterial, salt, pageLength);\n }\n\n /**\n * Creates a new `HKDFRng` with the default page length of 32 bytes.\n *\n * @param keyMaterial - The seed material to derive random numbers from\n * @param salt - A salt value to mix with the key material\n * @returns A new `HKDFRng` instance configured with the specified key material and salt\n */\n static new(keyMaterial: Uint8Array, salt: string): HKDFRng {\n return HKDFRng.newWithPageLength(keyMaterial, salt, DEFAULT_PAGE_LENGTH);\n }\n\n // ============================================================================\n // Private Methods\n // ============================================================================\n\n /**\n * Refills the internal buffer with new deterministic random bytes.\n *\n * This method is called automatically when the internal buffer is exhausted.\n * It uses HKDF-HMAC-SHA256 to generate a new page of random bytes using the\n * key material, salt, and current page index.\n */\n private fillBuffer(): void {\n const saltString = `${this._salt}-${this._pageIndex}`;\n const encoder = new TextEncoder();\n this._buffer = hkdfHmacSha256(this._keyMaterial, encoder.encode(saltString), this._pageLength);\n this._position = 0;\n this._pageIndex += 1;\n }\n\n /**\n * Generates the specified number of deterministic random bytes.\n *\n * @param length - The number of bytes to generate\n * @returns A Uint8Array containing the requested number of deterministic random bytes\n */\n private nextBytes(length: number): Uint8Array {\n const result: number[] = [];\n while (result.length < length) {\n if (this._position >= this._buffer.length) {\n this.fillBuffer();\n }\n const remaining = length - result.length;\n const available = this._buffer.length - this._position;\n const take = Math.min(remaining, available);\n for (let i = 0; i < take; i++) {\n result.push(this._buffer[this._position + i]);\n }\n this._position += take;\n }\n return new Uint8Array(result);\n }\n\n // ============================================================================\n // RandomNumberGenerator Implementation\n // ============================================================================\n\n /**\n * Generates deterministic random bytes.\n *\n * @param length - The number of bytes to generate\n * @returns A Uint8Array of random bytes\n */\n randomData(length: number): Uint8Array {\n return this.nextBytes(length);\n }\n\n /**\n * Fills the provided buffer with deterministic random bytes.\n *\n * @param dest - The buffer to fill with random bytes\n */\n fillBytes(dest: Uint8Array): void {\n const bytes = this.nextBytes(dest.length);\n dest.set(bytes);\n }\n\n // ============================================================================\n // Additional Methods (matching Rust RngCore interface)\n // ============================================================================\n\n /**\n * Generates a random `u32` value.\n *\n * @returns A deterministic random 32-bit unsigned integer\n */\n nextU32(): number {\n const bytes = this.nextBytes(4);\n // Little-endian byte order\n return bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24);\n }\n\n /**\n * Generates a random `u64` value.\n *\n * Note: JavaScript numbers can only safely represent integers up to 2^53 - 1,\n * so this returns a BigInt for full 64-bit precision.\n *\n * @returns A deterministic random 64-bit unsigned integer as BigInt\n */\n nextU64(): bigint {\n const bytes = this.nextBytes(8);\n // Little-endian byte order\n let result = BigInt(0);\n for (let i = 7; i >= 0; i--) {\n result = (result << BigInt(8)) | BigInt(bytes[i]);\n }\n return result;\n }\n\n /**\n * Attempts to fill the provided buffer with random bytes.\n * This implementation never fails.\n *\n * @param dest - The buffer to fill with random bytes\n */\n tryFillBytes(dest: Uint8Array): void {\n this.fillBytes(dest);\n }\n\n /**\n * Fills the provided buffer with deterministic random bytes.\n * Alias for fillBytes for interface compatibility.\n *\n * @param data - The buffer to fill with random bytes\n */\n fillRandomData(data: Uint8Array): void {\n this.fillBytes(data);\n }\n\n // ============================================================================\n // Accessors (for testing)\n // ============================================================================\n\n /**\n * Returns the key material (for testing purposes).\n */\n getKeyMaterial(): Uint8Array {\n return new Uint8Array(this._keyMaterial);\n }\n\n /**\n * Returns the salt (for testing purposes).\n */\n getSalt(): string {\n return this._salt;\n }\n\n /**\n * Returns the page length (for testing purposes).\n */\n getPageLength(): number {\n return this._pageLength;\n }\n\n /**\n * Returns the current page index (for testing purposes).\n */\n getPageIndex(): number {\n return this._pageIndex;\n }\n}\n","/**\n * DigestProvider interface for types that can provide a cryptographic digest.\n *\n * Ported from bc-components-rust/src/digest_provider.rs\n *\n * A type that can provide a single unique digest that characterizes its contents.\n * This trait is used to define a common interface for objects that can produce\n * a cryptographic digest (hash) of their content.\n *\n * @example\n * ```typescript\n * import { DigestProvider, Digest } from '@bcts/components';\n *\n * class Document implements DigestProvider {\n * private content: Uint8Array;\n * private cachedDigest?: Digest;\n *\n * constructor(content: Uint8Array) {\n * this.content = content;\n * }\n *\n * digest(): Digest {\n * if (!this.cachedDigest) {\n * this.cachedDigest = Digest.fromImage(this.content);\n * }\n * return this.cachedDigest;\n * }\n * }\n * ```\n */\nimport type { Digest } from \"./digest.js\";\n\n/**\n * A type that can provide a single unique digest that characterizes its contents.\n *\n * Use Cases:\n * - Data integrity verification\n * - Unique identifier for an object based on its content\n * - Content-addressable storage implementation\n * - Comparing objects by their content rather than identity\n */\nexport interface DigestProvider {\n /**\n * Returns a digest that uniquely characterizes the content of the\n * implementing type.\n */\n digest(): Digest;\n}\n\n/**\n * Helper function to get a digest from a byte array.\n * This provides DigestProvider-like functionality for raw bytes.\n *\n * @param data - The byte array to hash\n * @returns A Promise resolving to a Digest of the data\n */\nexport async function digestFromBytes(data: Uint8Array): Promise<Digest> {\n // Dynamic import to avoid circular dependency\n const { Digest } = await import(\"./digest.js\");\n return Digest.fromImage(data);\n}\n","/**\n * A random nonce (\"number used once\").\n *\n * Ported from bc-components-rust/src/nonce.rs\n *\n * A `Nonce` is a cryptographic primitive consisting of a random or\n * pseudo-random number that is used only once in a cryptographic\n * communication. Nonces are often used in authentication protocols, encryption\n * algorithms, and digital signatures to prevent replay attacks and ensure\n * the uniqueness of encrypted messages.\n *\n * In this implementation, a `Nonce` is a 12-byte random value. The size is\n * chosen to be sufficiently large to prevent collisions while remaining\n * efficient for storage and transmission.\n *\n * # CBOR Serialization\n *\n * `Nonce` implements the CBOR tagged encoding interfaces, which means it can be\n * serialized to and deserialized from CBOR with a specific tag (TAG_NONCE = 40014).\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `Nonce` is represented as a\n * binary blob with the type \"nonce\".\n *\n * # Common Uses\n *\n * - In authenticated encryption schemes like AES-GCM or ChaCha20-Poly1305\n * - For initializing counters in counter-mode block ciphers\n * - In challenge-response authentication protocols\n * - To prevent replay attacks in secure communications\n *\n * @example\n * ```typescript\n * import { Nonce } from '@bcts/components';\n *\n * // Generate a new random nonce\n * const nonce = Nonce.new();\n *\n * // Create a nonce from a byte array\n * const data = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);\n * const nonce2 = Nonce.fromData(data);\n *\n * // Access the nonce data\n * const nonceData = nonce2.data();\n * ```\n */\n\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\nimport { SYMMETRIC_NONCE_SIZE } from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { NONCE as TAG_NONCE } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"./error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"./utils.js\";\n\nexport class Nonce implements CborTaggedEncodable, CborTaggedDecodable<Nonce>, UREncodable {\n static readonly NONCE_SIZE = SYMMETRIC_NONCE_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== Nonce.NONCE_SIZE) {\n throw CryptoError.invalidSize(Nonce.NONCE_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new random nonce.\n */\n static new(): Nonce {\n const rng = new SecureRandomNumberGenerator();\n return new Nonce(rng.randomData(Nonce.NONCE_SIZE));\n }\n\n /**\n * Create a new random nonce (alias for compatibility).\n */\n static random(): Nonce {\n return Nonce.new();\n }\n\n /**\n * Restores a nonce from data.\n */\n static fromData(data: Uint8Array): Nonce {\n return new Nonce(new Uint8Array(data));\n }\n\n /**\n * Restores a nonce from data (validates length).\n */\n static fromDataRef(data: Uint8Array): Nonce {\n if (data.length !== Nonce.NONCE_SIZE) {\n throw CryptoError.invalidSize(Nonce.NONCE_SIZE, data.length);\n }\n return Nonce.fromData(data);\n }\n\n /**\n * Create a Nonce from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): Nonce {\n return Nonce.fromData(data);\n }\n\n /**\n * Create a new nonce from the given hexadecimal string.\n *\n * @throws Error if the string is not exactly 24 hexadecimal digits.\n */\n static fromHex(hex: string): Nonce {\n return new Nonce(hexToBytes(hex));\n }\n\n /**\n * Generate a random nonce using provided RNG.\n */\n static randomUsing(rng: SecureRandomNumberGenerator): Nonce {\n return new Nonce(rng.randomData(Nonce.NONCE_SIZE));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get the data of the nonce.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the nonce as a byte slice.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw nonce bytes as a copy.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * The data as a hexadecimal string.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Compare with another Nonce.\n */\n equals(other: Nonce): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `Nonce(${this.hex()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with Nonce.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_NONCE.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a Nonce by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): Nonce {\n const data = expectBytes(cbor);\n return Nonce.fromDataRef(data);\n }\n\n /**\n * Creates a Nonce by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): Nonce {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): Nonce {\n const instance = new Nonce(new Uint8Array(Nonce.NONCE_SIZE));\n return instance.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): Nonce {\n const cbor = decodeCbor(data);\n return Nonce.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): Nonce {\n const cbor = decodeCbor(data);\n const bytes = expectBytes(cbor);\n return Nonce.fromDataRef(bytes);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the Nonce.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"nonce\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a Nonce from a UR.\n */\n static fromUR(ur: UR): Nonce {\n ur.checkType(\"nonce\");\n const instance = new Nonce(new Uint8Array(Nonce.NONCE_SIZE));\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a Nonce from a UR string.\n */\n static fromURString(urString: string): Nonce {\n const ur = UR.fromURString(urString);\n return Nonce.fromUR(ur);\n }\n}\n","/**\n * Random salt used to decorrelate other information.\n *\n * Ported from bc-components-rust/src/salt.rs\n *\n * A `Salt` is a cryptographic primitive consisting of random data that is used\n * to modify the output of a cryptographic function. Salts are primarily used\n * in password hashing to defend against dictionary attacks, rainbow table\n * attacks, and pre-computation attacks. They are also used in other\n * cryptographic contexts to ensure uniqueness and prevent correlation between\n * different parts of a cryptosystem.\n *\n * Unlike a `Nonce` which has a fixed size, a `Salt` in this implementation can\n * have a variable length (minimum 8 bytes). Different salt creation methods\n * are provided to generate salts of appropriate sizes for different use cases.\n *\n * # Minimum Size Requirement\n *\n * For security reasons, salts must be at least 8 bytes long. Attempting to\n * create a salt with fewer than 8 bytes will result in an error.\n *\n * # CBOR Serialization\n *\n * `Salt` implements the CBOR tagged encoding interfaces, which means it can be\n * serialized to and deserialized from CBOR with a specific tag (TAG_SALT = 40018).\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `Salt` is represented as a\n * binary blob with the type \"salt\".\n *\n * # Common Uses\n *\n * - Password hashing and key derivation functions\n * - Preventing correlation in cryptographic protocols\n * - Randomizing data before encryption to prevent pattern recognition\n * - Adding entropy to improve security in various cryptographic functions\n *\n * @example\n * ```typescript\n * import { Salt } from '@bcts/components';\n *\n * // Generate a salt with 16 bytes\n * const salt = Salt.newWithLen(16);\n * console.log(salt.len()); // 16\n *\n * // Generate a salt proportional to 100 bytes of data\n * const salt2 = Salt.newForSize(100);\n *\n * // Generate a salt with length between 16 and 32 bytes\n * const salt3 = Salt.newInRange(16, 32);\n * ```\n */\n\nimport {\n SecureRandomNumberGenerator,\n type RandomNumberGenerator,\n rngNextInClosedRangeI32,\n} from \"@bcts/rand\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { SALT as TAG_SALT } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"./error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"./utils.js\";\n\nconst MIN_SALT_SIZE = 8;\n\nexport class Salt implements CborTaggedEncodable, CborTaggedDecodable<Salt>, UREncodable {\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new salt from data.\n * Note: Does not validate minimum size to allow for CBOR deserialization.\n */\n static fromData(data: Uint8Array): Salt {\n return new Salt(new Uint8Array(data));\n }\n\n /**\n * Create a Salt from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): Salt {\n return Salt.fromData(data);\n }\n\n /**\n * Create a new salt from the given hexadecimal string.\n */\n static fromHex(hex: string): Salt {\n return Salt.fromData(hexToBytes(hex));\n }\n\n /**\n * Create a specific number of bytes of salt.\n *\n * @throws Error if the number of bytes is less than 8.\n */\n static newWithLen(count: number): Salt {\n const rng = new SecureRandomNumberGenerator();\n return Salt.newWithLenUsing(count, rng);\n }\n\n /**\n * Create a specific number of bytes of salt using provided RNG.\n *\n * @throws Error if the number of bytes is less than 8.\n */\n static newWithLenUsing(count: number, rng: RandomNumberGenerator): Salt {\n if (count < MIN_SALT_SIZE) {\n throw CryptoError.dataTooShort(\"salt\", MIN_SALT_SIZE, count);\n }\n return new Salt(rng.randomData(count));\n }\n\n /**\n * Create a number of bytes of salt chosen randomly from the given range.\n *\n * @throws Error if the minimum number of bytes is less than 8.\n */\n static newInRange(minSize: number, maxSize: number): Salt {\n if (minSize < MIN_SALT_SIZE) {\n throw CryptoError.dataTooShort(\"salt\", MIN_SALT_SIZE, minSize);\n }\n const rng = new SecureRandomNumberGenerator();\n return Salt.newInRangeUsing(minSize, maxSize, rng);\n }\n\n /**\n * Create a number of bytes of salt chosen randomly from the given range using provided RNG.\n *\n * @throws Error if the minimum number of bytes is less than 8.\n */\n static newInRangeUsing(minSize: number, maxSize: number, rng: RandomNumberGenerator): Salt {\n if (minSize < MIN_SALT_SIZE) {\n throw CryptoError.dataTooShort(\"salt\", MIN_SALT_SIZE, minSize);\n }\n const count = rngNextInClosedRangeI32(rng, minSize, maxSize);\n return Salt.newWithLenUsing(count, rng);\n }\n\n /**\n * Create a number of bytes of salt generally proportionate to the size of\n * the object being salted.\n */\n static newForSize(size: number): Salt {\n const rng = new SecureRandomNumberGenerator();\n return Salt.newForSizeUsing(size, rng);\n }\n\n /**\n * Create a number of bytes of salt generally proportionate to the size of\n * the object being salted using provided RNG.\n */\n static newForSizeUsing(size: number, rng: RandomNumberGenerator): Salt {\n const count = size;\n const minSize = Math.max(MIN_SALT_SIZE, Math.ceil(count * 0.05));\n const maxSize = Math.max(minSize + 8, Math.ceil(count * 0.25));\n return Salt.newInRangeUsing(minSize, maxSize, rng);\n }\n\n /**\n * Generate a random salt with specified size (legacy alias for newWithLen).\n */\n static random(size = 16): Salt {\n return Salt.newWithLen(size);\n }\n\n /**\n * Generate a random salt with specified size using provided RNG (legacy alias).\n */\n static randomUsing(rng: RandomNumberGenerator, size = 16): Salt {\n return Salt.newWithLenUsing(size, rng);\n }\n\n /**\n * Generate a proportionally-sized salt (legacy alias for newForSize).\n */\n static proportional(dataSize: number): Salt {\n return Salt.newForSize(dataSize);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Return the length of the salt.\n */\n len(): number {\n return this._data.length;\n }\n\n /**\n * Return the length of the salt (alias for len).\n */\n size(): number {\n return this.len();\n }\n\n /**\n * Return true if the salt is empty (this is not recommended).\n */\n isEmpty(): boolean {\n return this._data.length === 0;\n }\n\n /**\n * Return the data of the salt.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw salt bytes as a copy.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * The data as a hexadecimal string.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Compare with another Salt.\n */\n equals(other: Salt): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation showing the salt's length.\n */\n toString(): string {\n return `Salt(${this.len()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with Salt.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SALT.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a Salt by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): Salt {\n const data = expectBytes(cbor);\n return Salt.fromData(data);\n }\n\n /**\n * Creates a Salt by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): Salt {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): Salt {\n const instance = new Salt(new Uint8Array(0));\n return instance.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): Salt {\n const cbor = decodeCbor(data);\n return Salt.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): Salt {\n const cbor = decodeCbor(data);\n const bytes = expectBytes(cbor);\n return Salt.fromData(bytes);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the Salt.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"salt\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a Salt from a UR.\n */\n static fromUR(ur: UR): Salt {\n ur.checkType(\"salt\");\n const instance = new Salt(new Uint8Array(0));\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a Salt from a UR string.\n */\n static fromURString(urString: string): Salt {\n const ur = UR.fromURString(urString);\n return Salt.fromUR(ur);\n }\n}\n","/**\n * Cryptographic seed with optional metadata (minimum 16 bytes)\n * Ported from bc-components-rust/src/seed.rs\n *\n * A `Seed` is a source of entropy used to generate cryptographic keys in a\n * deterministic manner. Unlike randomly generated keys, seed-derived keys can\n * be recreated if you have the original seed, making them useful for backup\n * and recovery scenarios.\n *\n * This implementation of `Seed` includes the random seed data as well as\n * optional metadata:\n * - A name (for identifying the seed)\n * - A note (for storing additional information)\n * - A creation date\n *\n * The minimum seed length is 16 bytes to ensure sufficient security and\n * entropy.\n *\n * # CBOR Serialization\n *\n * `Seed` implements the CBOR tagged encoding interfaces, which means it can be\n * serialized to and deserialized from CBOR with specific tags. The tags used\n * are `TAG_SEED` (40300) and the older `TAG_SEED_V1` (300) for backward compatibility.\n *\n * When serialized to CBOR, a `Seed` is represented as a map with the following\n * keys:\n * - 1: The seed data (required)\n * - 2: The creation date (optional)\n * - 3: The name (optional, omitted if empty)\n * - 4: The note (optional, omitted if empty)\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `Seed` is represented with the\n * type \"seed\".\n */\n\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n CborMap,\n CborDate,\n toByteString,\n expectMap,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { SEED as TAG_SEED, SEED_V1 as TAG_SEED_V1 } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"./error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"./utils.js\";\nimport type { PrivateKeyDataProvider } from \"./private-key-data-provider.js\";\n\nexport interface SeedMetadata {\n name?: string;\n note?: string;\n createdAt?: Date;\n}\n\nexport class Seed\n implements CborTaggedEncodable, CborTaggedDecodable<Seed>, UREncodable, PrivateKeyDataProvider\n{\n /**\n * Minimum seed length in bytes (matches Rust MIN_SEED_LENGTH).\n */\n static readonly MIN_SEED_LENGTH = 16;\n\n // Defensive copy: internal data is never exposed directly to prevent external mutation\n private readonly _data: Uint8Array;\n private _name: string;\n private _note: string;\n private _creationDate: Date | undefined;\n\n private constructor(data: Uint8Array, name?: string, note?: string, creationDate?: Date) {\n if (data.length < Seed.MIN_SEED_LENGTH) {\n throw CryptoError.dataTooShort(\"seed\", Seed.MIN_SEED_LENGTH, data.length);\n }\n // Defensive copy on construction to ensure immutability of internal state\n this._data = new Uint8Array(data);\n this._name = name ?? \"\";\n this._note = note ?? \"\";\n this._creationDate = creationDate;\n }\n\n // ============================================================================\n // Static Factory Methods (Rust API Parity)\n // ============================================================================\n\n /**\n * Create a new random seed with default length (16 bytes).\n *\n * Rust equivalent: `Seed::new()`\n */\n static new(): Seed {\n return Seed.newWithLen(Seed.MIN_SEED_LENGTH);\n }\n\n /**\n * Create a new random seed with a specified length.\n *\n * Rust equivalent: `Seed::new_with_len(count)`\n *\n * @param count - Number of bytes (must be >= 16)\n * @throws CryptoError if count < 16\n */\n static newWithLen(count: number): Seed {\n const rng = new SecureRandomNumberGenerator();\n return Seed.newWithLenUsing(count, rng);\n }\n\n /**\n * Create a new random seed with a specified length using provided RNG.\n *\n * Rust equivalent: `Seed::new_with_len_using(count, rng)`\n *\n * @param count - Number of bytes (must be >= 16)\n * @param rng - Random number generator\n * @throws CryptoError if count < 16\n */\n static newWithLenUsing(count: number, rng: { randomData: (size: number) => Uint8Array }): Seed {\n const data = rng.randomData(count);\n return Seed.newOpt(data, undefined, undefined, undefined);\n }\n\n /**\n * Create a new seed from data and optional metadata.\n *\n * Rust equivalent: `Seed::new_opt(data, name, note, creation_date)`\n *\n * @param data - Seed bytes (must be >= 16 bytes)\n * @param name - Optional name for the seed\n * @param note - Optional note for the seed\n * @param creationDate - Optional creation date\n * @throws CryptoError if data < 16 bytes\n */\n static newOpt(\n data: Uint8Array,\n name: string | undefined,\n note: string | undefined,\n creationDate: Date | undefined,\n ): Seed {\n return new Seed(data, name, note, creationDate);\n }\n\n // ============================================================================\n // Static Factory Methods (TypeScript Convenience)\n // ============================================================================\n\n /**\n * Create a Seed from raw bytes with optional metadata.\n *\n * Note: The input data is copied to prevent external mutation of the seed's internal state.\n *\n * @param data - Seed bytes (must be >= 16 bytes)\n * @param metadata - Optional metadata object\n */\n static from(data: Uint8Array, metadata?: SeedMetadata): Seed {\n return new Seed(new Uint8Array(data), metadata?.name, metadata?.note, metadata?.createdAt);\n }\n\n /**\n * Create a Seed from hex string with optional metadata.\n *\n * @param hex - Hex string representing seed bytes\n * @param metadata - Optional metadata object\n */\n static fromHex(hex: string, metadata?: SeedMetadata): Seed {\n return Seed.from(hexToBytes(hex), metadata);\n }\n\n /**\n * Generate a random seed with specified size (default 32 bytes).\n *\n * Convenience method that wraps `newWithLen()`.\n *\n * @param size - Number of bytes (must be >= 16, default 32)\n * @param metadata - Optional metadata object\n */\n static random(size = 32, metadata?: SeedMetadata): Seed {\n const seed = Seed.newWithLen(size);\n if (metadata?.name !== undefined) seed.setName(metadata.name);\n if (metadata?.note !== undefined) seed.setNote(metadata.note);\n if (metadata?.createdAt !== undefined) seed.setCreationDate(metadata.createdAt);\n return seed;\n }\n\n /**\n * Generate a random seed using provided RNG.\n *\n * Convenience method that wraps `newWithLenUsing()`.\n *\n * @param rng - Random number generator\n * @param size - Number of bytes (must be >= 16, default 32)\n * @param metadata - Optional metadata object\n */\n static randomUsing(\n rng: { randomData: (size: number) => Uint8Array },\n size = 32,\n metadata?: SeedMetadata,\n ): Seed {\n const seed = Seed.newWithLenUsing(size, rng);\n if (metadata?.name !== undefined) seed.setName(metadata.name);\n if (metadata?.note !== undefined) seed.setNote(metadata.note);\n if (metadata?.createdAt !== undefined) seed.setCreationDate(metadata.createdAt);\n return seed;\n }\n\n // ============================================================================\n // Instance Methods - Data Access (Rust API Parity)\n // ============================================================================\n\n /**\n * Return the data of the seed as a reference to the internal bytes.\n *\n * Rust equivalent: `seed.as_bytes()`\n *\n * Note: Returns a reference to internal data. For a copy, use `toData()`.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw seed bytes (copy).\n *\n * Note: Returns a copy to prevent external mutation of the seed's internal state.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n toHex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Get seed size in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n // ============================================================================\n // Instance Methods - Metadata Access (Rust API Parity)\n // ============================================================================\n\n /**\n * Return the name of the seed.\n *\n * Rust equivalent: `seed.name()` - returns empty string if not set.\n */\n name(): string {\n return this._name;\n }\n\n /**\n * Set the name of the seed.\n *\n * Rust equivalent: `seed.set_name(name)`\n */\n setName(name: string): void {\n this._name = name;\n }\n\n /**\n * Return the note of the seed.\n *\n * Rust equivalent: `seed.note()` - returns empty string if not set.\n */\n note(): string {\n return this._note;\n }\n\n /**\n * Set the note of the seed.\n *\n * Rust equivalent: `seed.set_note(note)`\n */\n setNote(note: string): void {\n this._note = note;\n }\n\n /**\n * Return the creation date of the seed.\n *\n * Rust equivalent: `seed.creation_date()`\n */\n creationDate(): Date | undefined {\n return this._creationDate;\n }\n\n /**\n * Set the creation date of the seed.\n *\n * Rust equivalent: `seed.set_creation_date(date)`\n */\n setCreationDate(creationDate: Date | undefined): void {\n this._creationDate = creationDate;\n }\n\n /**\n * Return the creation date of the seed (alias for creationDate).\n *\n * @deprecated Use `creationDate()` for Rust API parity.\n */\n createdAt(): Date | undefined {\n return this.creationDate();\n }\n\n /**\n * Set the creation date of the seed (alias for setCreationDate).\n *\n * @deprecated Use `setCreationDate()` for Rust API parity.\n */\n setCreatedAt(date: Date): void {\n this.setCreationDate(date);\n }\n\n /**\n * Get metadata as an object.\n *\n * TypeScript convenience method - returns a snapshot of current metadata.\n */\n getMetadata(): SeedMetadata {\n const metadata: SeedMetadata = {};\n if (this._name.length > 0) {\n metadata.name = this._name;\n }\n if (this._note.length > 0) {\n metadata.note = this._note;\n }\n if (this._creationDate !== undefined) {\n metadata.createdAt = this._creationDate;\n }\n return metadata;\n }\n\n // ============================================================================\n // Instance Methods - Comparison and Display\n // ============================================================================\n\n /**\n * Compare with another Seed.\n */\n equals(other: Seed): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `Seed(${this.toHex().substring(0, 16)}..., ${this.size()} bytes)`;\n }\n\n // ============================================================================\n // PrivateKeyDataProvider Implementation\n // ============================================================================\n\n /**\n * Returns unique data from which cryptographic keys can be derived.\n *\n * This implementation returns a copy of the seed data, which can be used\n * as entropy for deriving private keys in various cryptographic schemes.\n *\n * @returns A Uint8Array containing the seed data\n */\n privateKeyData(): Uint8Array {\n return this.toData();\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with Seed.\n * Includes TAG_SEED (40300) and TAG_SEED_V1 (300) for backward compatibility.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SEED.value, TAG_SEED_V1.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a map).\n * Map keys:\n * - 1: seed data (required)\n * - 2: creation date (optional)\n * - 3: name (optional, omitted if empty)\n * - 4: note (optional, omitted if empty)\n */\n untaggedCbor(): Cbor {\n const map = CborMap.new();\n map.insert(1, toByteString(this._data));\n if (this._creationDate !== undefined) {\n const cborDate = CborDate.fromDatetime(this._creationDate);\n map.insert(2, cborDate.taggedCbor());\n }\n if (this._name.length > 0) {\n map.insert(3, this._name);\n }\n if (this._note.length > 0) {\n map.insert(4, this._note);\n }\n return cbor(map);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a Seed by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): Seed {\n const map = expectMap(cborValue);\n\n // Key 1: seed data (required)\n // CborMap.extract() returns native types (Uint8Array for byte strings)\n const data = map.extract<number, Uint8Array>(1);\n if (data.length === 0) {\n throw CryptoError.invalidData(\"Seed data is empty\");\n }\n\n // Key 2: creation date (optional)\n // For tagged values (like dates), the extract returns the tagged Cbor object\n let creationDate: Date | undefined;\n const dateValue = map.get<number, Cbor>(2);\n if (dateValue !== undefined) {\n // The date is stored as a tagged CBOR value (tag 1)\n const cborDate = CborDate.fromTaggedCbor(cbor(dateValue));\n creationDate = cborDate.datetime();\n }\n\n // Key 3: name (optional)\n const name = map.get<number, string>(3);\n\n // Key 4: note (optional)\n const note = map.get<number, string>(4);\n\n return Seed.newOpt(new Uint8Array(data), name, note, creationDate);\n }\n\n /**\n * Creates a Seed by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): Seed {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): Seed {\n const instance = Seed.new();\n return instance.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): Seed {\n const cborValue = decodeCbor(data);\n return Seed.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): Seed {\n const cborValue = decodeCbor(data);\n const instance = Seed.new();\n return instance.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the Seed.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"seed\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a Seed from a UR.\n */\n static fromUR(ur: UR): Seed {\n ur.checkType(\"seed\");\n const instance = Seed.new();\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a Seed from a UR string.\n */\n static fromURString(urString: string): Seed {\n const ur = UR.fromURString(urString);\n return Seed.fromUR(ur);\n }\n}\n","/**\n * Content-addressable reference - SHA-256 digest with short reference encoding\n */\n\nimport { Digest } from \"./digest.js\";\nimport { CryptoError } from \"./error.js\";\n\nexport type ReferenceEncodingFormat = \"hex\" | \"bytewords\" | \"bytemojis\";\n\n/**\n * Implementers of this interface provide a globally unique reference to themselves.\n *\n * The `ReferenceProvider` interface is used to create a unique, cryptographic\n * reference to an object. This is particularly useful for distributed systems\n * where objects need to be uniquely identified across networks or storage\n * systems.\n *\n * The reference is derived from a cryptographic digest of the object's\n * serialized form, ensuring that the reference uniquely identifies the\n * object's contents.\n */\nexport interface ReferenceProvider {\n /**\n * Returns a cryptographic reference that uniquely identifies this object.\n *\n * The reference is derived from a digest of the object's serialized form,\n * ensuring that it uniquely identifies the object's contents.\n */\n reference(): Reference;\n}\n\n/**\n * Type guard to check if an object implements the ReferenceProvider interface.\n */\nexport function isReferenceProvider(obj: unknown): obj is ReferenceProvider {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"reference\" in obj &&\n typeof (obj as ReferenceProvider).reference === \"function\"\n );\n}\n\n// Bytewords mapping (256 words)\nconst BYTEWORDS = [\n \"abled\",\n \"ache\",\n \"acid\",\n \"acme\",\n \"acre\",\n \"aged\",\n \"aide\",\n \"airy\",\n \"ajar\",\n \"akin\",\n \"alas\",\n \"alba\",\n \"alee\",\n \"alms\",\n \"aloe\",\n \"also\",\n \"ante\",\n \"anti\",\n \"ants\",\n \"anus\",\n \"anus\",\n \"apes\",\n \"apex\",\n \"apse\",\n \"arch\",\n \"area\",\n \"ares\",\n \"aria\",\n \"arid\",\n \"ark\",\n \"arms\",\n \"army\",\n // ... (256 total - abbreviated for space)\n];\n\n// Bytemojis mapping (256 emojis)\nconst BYTEMOJIS = [\n \"😀\",\n \"😂\",\n \"😆\",\n \"😉\",\n \"😊\",\n \"😌\",\n \"😎\",\n \"😏\",\n \"😑\",\n \"😒\",\n \"😓\",\n \"😔\",\n \"😕\",\n \"😖\",\n \"😗\",\n \"😘\",\n // ... (256 total - abbreviated for space)\n];\n\nexport class Reference {\n private readonly digest: Digest;\n\n private constructor(digest: Digest) {\n this.digest = digest;\n }\n\n /**\n * Create a Reference from a Digest\n */\n static from(digest: Digest): Reference {\n return new Reference(digest);\n }\n\n /**\n * Create a Reference from hex string\n */\n static fromHex(hex: string): Reference {\n const digest = Digest.fromHex(hex);\n return new Reference(digest);\n }\n\n /**\n * Generate a Reference from data\n */\n static hash(data: Uint8Array): Reference {\n const digest = Digest.hash(data);\n return new Reference(digest);\n }\n\n /**\n * Get the underlying Digest\n */\n getDigest(): Digest {\n return this.digest;\n }\n\n /**\n * Get full reference as hex string\n */\n toHex(): string {\n return this.digest.toHex();\n }\n\n /**\n * Get short reference (first 4 bytes) in various formats\n */\n shortReference(format: ReferenceEncodingFormat = \"hex\"): string {\n const data = this.digest.toData();\n const shortData = data.slice(0, 4);\n\n switch (format) {\n case \"hex\":\n // Lowercase hex, matching Rust implementation\n return Array.from(shortData)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n\n case \"bytewords\":\n return Array.from(shortData)\n .map((b) => BYTEWORDS[b] ?? `word${b}`)\n .join(\" \");\n\n case \"bytemojis\":\n return Array.from(shortData)\n .map((b) => BYTEMOJIS[b] ?? \"❓\")\n .join(\" \");\n\n default: {\n const _exhaustive: never = format;\n throw CryptoError.invalidFormat(`Unknown reference format: ${String(_exhaustive)}`);\n }\n }\n }\n\n /**\n * Get full reference as hex string (alias for toHex)\n */\n fullReference(): string {\n return this.toHex();\n }\n\n /**\n * Get short reference as hex string.\n * Convenience method for parity with Rust's ref_hex_short().\n */\n refHexShort(): string {\n return this.shortReference(\"hex\");\n }\n\n /**\n * Get base64 representation\n */\n toBase64(): string {\n return this.digest.toBase64();\n }\n\n /**\n * Compare with another Reference\n */\n equals(other: Reference): boolean {\n return this.digest.equals(other.digest);\n }\n\n /**\n * Get string representation\n */\n toString(): string {\n return `Reference(${this.shortReference(\"hex\")})`;\n }\n}\n","/**\n * An \"Apparently Random Identifier\" (ARID)\n *\n * Ported from bc-components-rust/src/id/arid.rs\n *\n * An ARID is a cryptographically strong, universally unique identifier with\n * the following properties:\n * - Non-correlatability: The sequence of bits cannot be correlated with its\n * referent or any other ARID\n * - Neutral semantics: Contains no inherent type information\n * - Open generation: Any method of generation is allowed as long as it\n * produces statistically random bits\n * - Minimum strength: Must be 256 bits (32 bytes) in length\n * - Cryptographic suitability: Can be used as inputs to cryptographic\n * constructs\n *\n * Unlike digests/hashes which identify a fixed, immutable state of data, ARIDs\n * can serve as stable identifiers for mutable data structures.\n *\n * ARIDs should not be confused with or cast to/from other identifier types\n * (like UUIDs), used as nonces, keys, or cryptographic seeds.\n *\n * As defined in [BCR-2022-002](https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2022-002-arid.md).\n *\n * # CBOR Serialization\n *\n * `ARID` implements the CBOR tagged encoding interfaces, which means it can be\n * serialized to and deserialized from CBOR with a specific tag (TAG_ARID = 40012).\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), an `ARID` is represented as a\n * binary blob with the type \"arid\".\n *\n * @example\n * ```typescript\n * import { ARID } from '@bcts/components';\n *\n * // Create a new random ARID\n * const arid = ARID.new();\n *\n * // Create an ARID from a hex string\n * const arid2 = ARID.fromHex(\"...\");\n *\n * // Get the ARID as hex\n * console.log(arid.hex());\n * ```\n */\n\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { ARID as TAG_ARID } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\n\nexport class ARID implements CborTaggedEncodable, CborTaggedDecodable<ARID>, UREncodable {\n static readonly ARID_SIZE = 32;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== ARID.ARID_SIZE) {\n throw CryptoError.invalidSize(ARID.ARID_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new random ARID.\n */\n static new(): ARID {\n const rng = new SecureRandomNumberGenerator();\n return new ARID(rng.randomData(ARID.ARID_SIZE));\n }\n\n /**\n * Create a new random ARID (alias for new()).\n */\n static random(): ARID {\n return ARID.new();\n }\n\n /**\n * Restore an ARID from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): ARID {\n return new ARID(new Uint8Array(data));\n }\n\n /**\n * Create a new ARID from a reference to an array of bytes.\n */\n static fromDataRef(data: Uint8Array): ARID {\n if (data.length !== ARID.ARID_SIZE) {\n throw CryptoError.invalidSize(ARID.ARID_SIZE, data.length);\n }\n return ARID.fromData(data);\n }\n\n /**\n * Create an ARID from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): ARID {\n return ARID.fromData(data);\n }\n\n /**\n * Create a new ARID from the given hexadecimal string.\n *\n * @throws Error if the string is not exactly 64 hexadecimal digits.\n */\n static fromHex(hex: string): ARID {\n return new ARID(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get the data of the ARID as an array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the data of the ARID as a byte slice.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw ARID bytes as a copy.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * The data as a hexadecimal string.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * The first four bytes of the ARID as a hexadecimal string.\n */\n shortDescription(): string {\n return bytesToHex(this._data.slice(0, 4));\n }\n\n /**\n * Compare with another ARID.\n */\n equals(other: ARID): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Compare ARIDs lexicographically.\n */\n compare(other: ARID): number {\n for (let i = 0; i < this._data.length; i++) {\n const a = this._data[i];\n const b = other._data[i];\n if (a < b) return -1;\n if (a > b) return 1;\n }\n return 0;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `ARID(${this.hex()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with ARID.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_ARID.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an ARID by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): ARID {\n const data = expectBytes(cbor);\n return ARID.fromDataRef(data);\n }\n\n /**\n * Creates an ARID by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): ARID {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): ARID {\n const instance = new ARID(new Uint8Array(ARID.ARID_SIZE));\n return instance.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): ARID {\n const cbor = decodeCbor(data);\n return ARID.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): ARID {\n const cbor = decodeCbor(data);\n const bytes = expectBytes(cbor);\n return ARID.fromDataRef(bytes);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the ARID.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"arid\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an ARID from a UR.\n */\n static fromUR(ur: UR): ARID {\n ur.checkType(\"arid\");\n const instance = new ARID(new Uint8Array(ARID.ARID_SIZE));\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an ARID from a UR string.\n */\n static fromURString(urString: string): ARID {\n const ur = UR.fromURString(urString);\n return ARID.fromUR(ur);\n }\n\n /**\n * Alias for fromURString for Rust API compatibility.\n */\n static fromUrString(urString: string): ARID {\n return ARID.fromURString(urString);\n }\n}\n","/**\n * Universally Unique Identifier (UUID) - 16-byte identifier\n *\n * UUIDs are 128-bit (16-byte) identifiers that are designed to be unique\n * across space and time. This implementation creates type 4 (random) UUIDs,\n * following the UUID specification:\n *\n * - Version field (bits 48-51) is set to 4, indicating a random UUID\n * - Variant field (bits 64-65) is set to 2, indicating RFC 4122/DCE 1.1 UUID\n * variant\n *\n * Unlike ARIDs, UUIDs:\n * - Are shorter (128 bits vs 256 bits)\n * - Contain version and variant metadata within the identifier\n * - Have a canonical string representation with 5 groups separated by hyphens\n *\n * The canonical textual representation of a UUID takes the form:\n * `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` where each `x` is a hexadecimal digit.\n *\n * # CBOR Serialization\n *\n * `UUID` is serialized to CBOR with tag 37 (standard UUID tag).\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `UUID` is represented with the\n * type \"uuid\".\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UUID as TAG_UUID } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, toBase64 } from \"../utils.js\";\n\nconst UUID_SIZE = 16;\n\nexport class UUID implements CborTaggedEncodable, CborTaggedDecodable<UUID>, UREncodable {\n static readonly UUID_SIZE = UUID_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== UUID_SIZE) {\n throw CryptoError.invalidSize(UUID_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new random UUID (v4).\n */\n static new(): UUID {\n return UUID.random();\n }\n\n /**\n * Create a UUID from raw bytes.\n */\n static fromData(data: Uint8Array): UUID {\n return new UUID(new Uint8Array(data));\n }\n\n /**\n * Restores a UUID from data (validates length).\n */\n static fromDataRef(data: Uint8Array): UUID {\n if (data.length !== UUID_SIZE) {\n throw CryptoError.invalidSize(UUID_SIZE, data.length);\n }\n return UUID.fromData(data);\n }\n\n /**\n * Create a UUID from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): UUID {\n return UUID.fromData(data);\n }\n\n /**\n * Create a UUID from hex string (32 hex chars)\n */\n static fromHex(hex: string): UUID {\n if (hex.length !== 32) {\n throw CryptoError.invalidFormat(`UUID hex must be 32 characters, got ${hex.length}`);\n }\n const data = new Uint8Array(16);\n for (let i = 0; i < 16; i++) {\n data[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);\n }\n return new UUID(data);\n }\n\n /**\n * Create a UUID from string representation (standard UUID format)\n * Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n */\n static fromString(uuidString: string): UUID {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n if (!uuidRegex.test(uuidString)) {\n throw CryptoError.invalidFormat(`Invalid UUID format: ${uuidString}`);\n }\n const hex = uuidString.replace(/-/g, \"\");\n return UUID.fromHex(hex);\n }\n\n /**\n * Generate a random UUID (v4)\n */\n static random(): UUID {\n const data = new Uint8Array(UUID_SIZE);\n globalThis.crypto.getRandomValues(data);\n\n // Set version to 4 (random)\n data[6] = (data[6] & 0x0f) | 0x40;\n // Set variant to RFC 4122\n data[8] = (data[8] & 0x3f) | 0x80;\n\n return new UUID(data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get the data of the UUID.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the UUID as a byte slice.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw UUID bytes as a copy.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation (lowercase, matching Rust implementation).\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get standard UUID string representation.\n * Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n */\n toString(): string {\n const hex = this.toHex();\n return `${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}`;\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Compare with another UUID.\n */\n equals(other: UUID): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with UUID.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_UUID.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a UUID by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): UUID {\n const data = expectBytes(cbor);\n return UUID.fromDataRef(data);\n }\n\n /**\n * Creates a UUID by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): UUID {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): UUID {\n const instance = new UUID(new Uint8Array(UUID_SIZE));\n return instance.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): UUID {\n const cbor = decodeCbor(data);\n return UUID.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): UUID {\n const cbor = decodeCbor(data);\n const bytes = expectBytes(cbor);\n return UUID.fromDataRef(bytes);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the UUID.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"uuid\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a UUID from a UR.\n */\n static fromUR(ur: UR): UUID {\n ur.checkType(\"uuid\");\n const instance = new UUID(new Uint8Array(UUID_SIZE));\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a UUID from a UR string.\n */\n static fromURString(urString: string): UUID {\n const ur = UR.fromURString(urString);\n return UUID.fromUR(ur);\n }\n}\n","/**\n * eXtensible Identifier (XID) - 32-byte identifier bound to a public key\n *\n * A XID is a unique 32-byte identifier for a subject entity (person,\n * organization, device, or any other entity). XIDs have the following\n * characteristics:\n *\n * - They're cryptographically tied to a public key at inception (the\n * \"inception key\")\n * - They remain stable throughout their lifecycle even as their keys and\n * permissions change\n * - They can be extended to XID documents containing keys, endpoints,\n * permissions, and delegation info\n * - They support key rotation and multiple verification schemes\n * - They allow for delegation of specific permissions to other entities\n * - They can include resolution methods to locate and verify the XID document\n *\n * A XID is created by taking the SHA-256 hash of the CBOR encoding of a public\n * signing key. This ensures the XID is cryptographically tied to the key.\n *\n * As defined in [BCR-2024-010](https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2024-010-xid.md).\n *\n * # CBOR Serialization\n *\n * `XID` is serialized to CBOR with tag 40024 (standard XID tag).\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `XID` is represented with the\n * type \"xid\".\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { XID as TAG_XID } from \"@bcts/tags\";\nimport {\n UR,\n type UREncodable,\n encodeBytewordsIdentifier,\n encodeBytemojisIdentifier,\n} from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, toBase64 } from \"../utils.js\";\nimport { Digest } from \"../digest.js\";\nimport type { SigningPublicKey } from \"../signing/signing-public-key.js\";\n\n/** XID prefix for bytewords/bytemoji identifiers */\nconst XID_PREFIX = \"🅧\";\n\nconst XID_SIZE = 32;\n\nexport class XID implements CborTaggedEncodable, CborTaggedDecodable<XID>, UREncodable {\n static readonly XID_SIZE = XID_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== XID_SIZE) {\n throw CryptoError.invalidSize(XID_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new XID from data.\n */\n static fromData(data: Uint8Array): XID {\n return new XID(new Uint8Array(data));\n }\n\n /**\n * Create a new XID from data (validates length).\n *\n * Returns error if the data is not the correct length.\n */\n static fromDataRef(data: Uint8Array): XID {\n if (data.length !== XID_SIZE) {\n throw CryptoError.invalidSize(XID_SIZE, data.length);\n }\n return XID.fromData(data);\n }\n\n /**\n * Create an XID from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): XID {\n return XID.fromData(data);\n }\n\n /**\n * Create an XID from hex string (64 hex characters).\n */\n static fromHex(hex: string): XID {\n if (hex.length !== 64) {\n throw CryptoError.invalidFormat(`XID hex must be 64 characters, got ${hex.length}`);\n }\n const data = new Uint8Array(32);\n for (let i = 0; i < 32; i++) {\n data[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);\n }\n return new XID(data);\n }\n\n /**\n * Generate a random XID (for testing purposes).\n *\n * Note: In practice, XIDs should be created from the SHA-256 hash of a\n * public signing key's CBOR encoding.\n */\n static random(): XID {\n const data = new Uint8Array(XID_SIZE);\n const crypto = globalThis.crypto as Crypto | undefined;\n if (crypto !== undefined && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(data);\n } else {\n // Fallback: fill with available random data\n for (let i = 0; i < XID_SIZE; i++) {\n data[i] = Math.floor(Math.random() * 256);\n }\n }\n return new XID(data);\n }\n\n /**\n * Create a new XID from the given public key (the \"genesis key\").\n *\n * The XID is the SHA-256 digest of the CBOR encoding of the public key.\n * This matches Rust's `XID::new(genesis_key: impl AsRef<SigningPublicKey>)`.\n */\n static newFromSigningKey(signingPublicKey: SigningPublicKey): XID {\n const keyCborData = signingPublicKey.taggedCborData();\n const digest = Digest.fromImage(keyCborData);\n return XID.fromData(digest.toData());\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Validate the XID against the given public key.\n *\n * Returns true if the SHA-256 hash of the key's CBOR encoding matches\n * the XID data. This matches Rust's `XID::validate(&self, key: &SigningPublicKey)`.\n */\n validate(signingPublicKey: SigningPublicKey): boolean {\n const keyData = signingPublicKey.taggedCborData();\n const digest = Digest.fromImage(keyData);\n return this.equals(XID.fromData(digest.toData()));\n }\n\n /**\n * Return the data of the XID.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the data of the XID as a byte slice.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get a copy of the raw XID bytes.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation (lowercase, matching Rust implementation).\n */\n toHex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Get short description (first 4 bytes) as hex.\n */\n shortDescription(): string {\n return bytesToHex(this._data.slice(0, 4));\n }\n\n /**\n * Get short reference (first 4 bytes) as hex (alias for shortDescription).\n */\n shortReference(): string {\n return this.shortDescription();\n }\n\n /**\n * Get the first four bytes of the XID as upper-case ByteWords.\n *\n * @param prefix - If true, prepends the XID prefix \"🅧 \"\n * @returns Space-separated uppercase bytewords, e.g., \"🅧 URGE DICE GURU IRIS\"\n */\n bytewordsIdentifier(prefix = false): string {\n const words = encodeBytewordsIdentifier(this._data.slice(0, 4)).toUpperCase();\n return prefix ? `${XID_PREFIX} ${words}` : words;\n }\n\n /**\n * Get the first four bytes of the XID as Bytemoji.\n *\n * @param prefix - If true, prepends the XID prefix \"🅧 \"\n * @returns Space-separated emojis, e.g., \"🅧 🐻 😻 🍞 💐\"\n */\n bytemojisIdentifier(prefix = false): string {\n const emojis = encodeBytemojisIdentifier(this._data.slice(0, 4));\n return prefix ? `${XID_PREFIX} ${emojis}` : emojis;\n }\n\n /**\n * Compare with another XID.\n */\n equals(other: XID): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation (short format, matching Rust Display).\n * Uses first 4 bytes of the XID as hex, e.g., \"XID(71274df1)\".\n */\n toString(): string {\n return `XID(${this.shortDescription()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with XID.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_XID.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a XID by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): XID {\n const data = expectBytes(cbor);\n return XID.fromDataRef(data);\n }\n\n /**\n * Creates a XID by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): XID {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): XID {\n const instance = new XID(new Uint8Array(XID_SIZE));\n return instance.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): XID {\n const cbor = decodeCbor(data);\n return XID.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): XID {\n const cbor = decodeCbor(data);\n const bytes = expectBytes(cbor);\n return XID.fromDataRef(bytes);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the XID.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"xid\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a XID from a UR.\n */\n static fromUR(ur: UR): XID {\n ur.checkType(\"xid\");\n const instance = new XID(new Uint8Array(XID_SIZE));\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a XID from a UR string.\n */\n static fromURString(urString: string): XID {\n const ur = UR.fromURString(urString);\n return XID.fromUR(ur);\n }\n}\n","/**\n * Uniform Resource Identifier (URI) - String-based identifier\n *\n * A URI is a string of characters that unambiguously identifies a particular\n * resource. This implementation validates URIs using the URL API to ensure\n * conformance to RFC 3986.\n *\n * URIs are commonly used for:\n * - Web addresses (URLs like \"https://example.com\")\n * - Resource identifiers in various protocols\n * - Namespace identifiers\n * - References to resources in distributed systems\n *\n * # CBOR Serialization\n *\n * `URI` is serialized to CBOR with tag 32 (standard URI tag).\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `URI` is represented with the\n * type \"url\".\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectText,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { URI as TAG_URI } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"../error.js\";\nimport { toBase64 } from \"../utils.js\";\n\nexport class URI implements CborTaggedEncodable, CborTaggedDecodable<URI>, UREncodable {\n private readonly _uri: string;\n\n private constructor(uri: string) {\n this._uri = uri;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Creates a new `URI` from a string with validation.\n */\n static new(uri: string): URI {\n // Validate using URL API\n try {\n new URL(uri);\n return new URI(uri);\n } catch {\n throw CryptoError.invalidData(\"URI: invalid URI format\");\n }\n }\n\n /**\n * Create a URI from string (legacy alias).\n */\n static from(uri: string): URI {\n return URI.new(uri);\n }\n\n /**\n * Parse a URI string (alias for new()).\n */\n static parse(uriString: string): URI {\n return URI.new(uriString);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get the URI as a string reference.\n */\n asRef(): string {\n return this._uri;\n }\n\n /**\n * Get the URI string.\n */\n toString(): string {\n return this._uri;\n }\n\n /**\n * Get the URI string (alias).\n */\n toURI(): string {\n return this._uri;\n }\n\n /**\n * Get the raw URI string.\n */\n getRaw(): string {\n return this._uri;\n }\n\n /**\n * Get scheme (e.g., \"http\", \"https\", \"urn\").\n */\n scheme(): string | null {\n const match = /^([a-z][a-z0-9+.-]*):\\/?\\/?/i.exec(this._uri);\n return match !== null ? match[1] : null;\n }\n\n /**\n * Get path component.\n */\n path(): string {\n try {\n const url = new URL(this._uri);\n return url.pathname;\n } catch {\n // For non-URL URIs, try to extract path after scheme\n const withoutScheme = this._uri.replace(/^[a-z][a-z0-9+.-]*:\\/?\\/?/i, \"\");\n return withoutScheme;\n }\n }\n\n /**\n * Check if URI is absolute (has a scheme).\n */\n isAbsolute(): boolean {\n return /^[a-z][a-z0-9+.-]*:/i.test(this._uri);\n }\n\n /**\n * Check if URI is relative.\n */\n isRelative(): boolean {\n return !this.isAbsolute();\n }\n\n /**\n * Compare with another URI.\n */\n equals(other: URI): boolean {\n return this._uri === other._uri;\n }\n\n /**\n * Check if URI starts with given prefix.\n */\n startsWith(prefix: string): boolean {\n return this._uri.startsWith(prefix);\n }\n\n /**\n * Get base64 representation of the URI string.\n */\n toBase64(): string {\n return toBase64(new TextEncoder().encode(this._uri));\n }\n\n /**\n * Get the length of the URI string.\n */\n length(): number {\n return this._uri.length;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with URI.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_URI.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a text string).\n */\n untaggedCbor(): Cbor {\n return cbor(this._uri);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a URI by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): URI {\n const text = expectText(cborValue);\n return URI.new(text);\n }\n\n /**\n * Creates a URI by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): URI {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): URI {\n const instance = new URI(\"https://placeholder.invalid\");\n return instance.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): URI {\n const cborValue = decodeCbor(data);\n return URI.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): URI {\n const cborValue = decodeCbor(data);\n const text = expectText(cborValue);\n return URI.new(text);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the URI.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"url\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a URI from a UR.\n */\n static fromUR(ur: UR): URI {\n ur.checkType(\"url\");\n const instance = new URI(\"https://placeholder.invalid\");\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a URI from a UR string.\n */\n static fromURString(urString: string): URI {\n const ur = UR.fromURString(urString);\n return URI.fromUR(ur);\n }\n}\n","/**\n * X25519 public key for ECDH key exchange (32 bytes)\n *\n * X25519 is an elliptic-curve Diffie-Hellman key exchange protocol based on\n * Curve25519 as defined in RFC 7748. It allows two parties to establish a\n * shared secret key over an insecure channel.\n *\n * The X25519 public key is generated from a corresponding private key and is\n * designed to be:\n * - Compact (32 bytes)\n * - Fast to use in key agreement operations\n * - Resistant to various cryptographic attacks\n *\n * # CBOR Serialization\n *\n * `X25519PublicKey` is serialized to CBOR with tag 40011.\n *\n * ```\n * #6.40011(h'<32-byte-public-key>')\n * ```\n *\n * Ported from bc-components-rust/src/x25519/x25519_public_key.rs\n */\n\nimport { X25519_PUBLIC_KEY_SIZE } from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { X25519_PUBLIC_KEY as TAG_X25519_PUBLIC_KEY } from \"@bcts/tags\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\n\nexport class X25519PublicKey\n implements CborTaggedEncodable, CborTaggedDecodable<X25519PublicKey>, UREncodable\n{\n static readonly KEY_SIZE = X25519_PUBLIC_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== X25519_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(X25519_PUBLIC_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Restore an X25519PublicKey from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): X25519PublicKey {\n return new X25519PublicKey(new Uint8Array(data));\n }\n\n /**\n * Restore an X25519PublicKey from a reference to an array of bytes.\n * Validates the length.\n */\n static fromDataRef(data: Uint8Array): X25519PublicKey {\n if (data.length !== X25519_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(X25519_PUBLIC_KEY_SIZE, data.length);\n }\n return X25519PublicKey.fromData(data);\n }\n\n /**\n * Create an X25519PublicKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): X25519PublicKey {\n return X25519PublicKey.fromData(data);\n }\n\n /**\n * Restore an X25519PublicKey from a hex string.\n */\n static fromHex(hex: string): X25519PublicKey {\n return X25519PublicKey.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw public key bytes (copy).\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Compare with another X25519PublicKey.\n */\n equals(other: X25519PublicKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `X25519PublicKey(${this.toHex().substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with X25519PublicKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_X25519_PUBLIC_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an X25519PublicKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): X25519PublicKey {\n const data = expectBytes(cbor);\n return X25519PublicKey.fromDataRef(data);\n }\n\n /**\n * Creates an X25519PublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): X25519PublicKey {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): X25519PublicKey {\n const dummy = new X25519PublicKey(new Uint8Array(X25519_PUBLIC_KEY_SIZE));\n return dummy.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): X25519PublicKey {\n const cbor = decodeCbor(data);\n return X25519PublicKey.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): X25519PublicKey {\n const cbor = decodeCbor(data);\n const dummy = new X25519PublicKey(new Uint8Array(X25519_PUBLIC_KEY_SIZE));\n return dummy.fromUntaggedCbor(cbor);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the X25519PublicKey.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n const name = TAG_X25519_PUBLIC_KEY.name;\n if (name === undefined) {\n throw new Error(\"X25519_PUBLIC_KEY tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an X25519PublicKey from a UR.\n */\n static fromUR(ur: UR): X25519PublicKey {\n const name = TAG_X25519_PUBLIC_KEY.name;\n if (name === undefined) {\n throw new Error(\"X25519_PUBLIC_KEY tag name is undefined\");\n }\n ur.checkType(name);\n const dummy = new X25519PublicKey(new Uint8Array(X25519_PUBLIC_KEY_SIZE));\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an X25519PublicKey from a UR string.\n */\n static fromURString(urString: string): X25519PublicKey {\n const ur = UR.fromURString(urString);\n return X25519PublicKey.fromUR(ur);\n }\n}\n","/**\n * Authentication tag for AEAD encryption (16 bytes)\n *\n * An `AuthenticationTag` is a 16-byte value generated during ChaCha20-Poly1305\n * authenticated encryption. It serves as a message authentication code (MAC)\n * that verifies both the authenticity and integrity of the encrypted message.\n *\n * During decryption, the tag is verified to ensure:\n * - The message has not been tampered with (integrity)\n * - The message was encrypted by someone who possesses the encryption key\n * (authenticity)\n *\n * This implementation follows the Poly1305 MAC algorithm as specified in\n * [RFC-8439](https://datatracker.ietf.org/doc/html/rfc8439).\n *\n * Ported from bc-components-rust/src/symmetric/authentication_tag.rs\n */\n\nimport { type Cbor, toByteString, expectBytes, decodeCbor } from \"@bcts/dcbor\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\n\nconst AUTHENTICATION_TAG_SIZE = 16;\n\nexport class AuthenticationTag {\n static readonly AUTHENTICATION_TAG_SIZE = AUTHENTICATION_TAG_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== AUTHENTICATION_TAG_SIZE) {\n throw CryptoError.invalidSize(AUTHENTICATION_TAG_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Restore an AuthenticationTag from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): AuthenticationTag {\n return new AuthenticationTag(new Uint8Array(data));\n }\n\n /**\n * Restore an AuthenticationTag from a reference to an array of bytes.\n */\n static fromDataRef(data: Uint8Array): AuthenticationTag {\n if (data.length !== AUTHENTICATION_TAG_SIZE) {\n throw CryptoError.invalidSize(AUTHENTICATION_TAG_SIZE, data.length);\n }\n return AuthenticationTag.fromData(data);\n }\n\n /**\n * Create an AuthenticationTag from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): AuthenticationTag {\n return AuthenticationTag.fromData(data);\n }\n\n /**\n * Create an AuthenticationTag from hex string.\n */\n static fromHex(hex: string): AuthenticationTag {\n return AuthenticationTag.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the reference as a byte slice.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw tag bytes as a copy.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n toHex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Compare with another AuthenticationTag.\n */\n equals(other: AuthenticationTag): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `AuthenticationTag(${this.toHex()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (untagged - no CBOR tag for AuthenticationTag)\n // ============================================================================\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n * AuthenticationTag has no CBOR tag - it's serialized as a plain byte string.\n */\n toCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the CBOR binary representation.\n */\n toCborData(): Uint8Array {\n return this.toCbor().toData();\n }\n\n /**\n * Creates an AuthenticationTag from CBOR.\n */\n static fromCbor(cbor: Cbor): AuthenticationTag {\n const data = expectBytes(cbor);\n return AuthenticationTag.fromDataRef(data);\n }\n\n /**\n * Creates an AuthenticationTag from CBOR binary data.\n */\n static fromCborData(data: Uint8Array): AuthenticationTag {\n const cbor = decodeCbor(data);\n return AuthenticationTag.fromCbor(cbor);\n }\n}\n","/**\n * Encrypted message with ChaCha20-Poly1305 AEAD\n *\n * A secure encrypted message using IETF ChaCha20-Poly1305 authenticated\n * encryption.\n *\n * `EncryptedMessage` represents data that has been encrypted using a symmetric\n * key with the ChaCha20-Poly1305 AEAD (Authenticated Encryption with\n * Associated Data) construction as specified in [RFC-8439](https://datatracker.ietf.org/doc/html/rfc8439).\n *\n * An `EncryptedMessage` contains:\n * - `ciphertext`: The encrypted data (same length as the original plaintext)\n * - `aad`: Additional Authenticated Data that is not encrypted but is\n * authenticated (optional)\n * - `nonce`: A 12-byte number used once for this specific encryption operation\n * - `auth`: A 16-byte authentication tag that verifies the integrity of the\n * message\n *\n * The `aad` field is often used to include the `Digest` of the plaintext,\n * which allows verification of the plaintext after decryption and preserves\n * the unique identity of the data when used with structures like Gordian\n * Envelope.\n *\n * # CBOR Serialization\n *\n * `EncryptedMessage` is serialized to CBOR with tag 40002.\n *\n * CDDL:\n * ```cddl\n * EncryptedMessage =\n * #6.40002([ ciphertext: bstr, nonce: bstr, auth: bstr, ? aad: bstr ])\n * ```\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), an `EncryptedMessage` is\n * represented with the type \"encrypted\".\n *\n * Ported from bc-components-rust/src/symmetric/encrypted_message.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectArray,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { ENCRYPTED as TAG_ENCRYPTED } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { Nonce } from \"../nonce.js\";\nimport { Digest } from \"../digest.js\";\nimport { AuthenticationTag } from \"./authentication-tag.js\";\nimport { bytesToHex } from \"../utils.js\";\n\nexport class EncryptedMessage\n implements CborTaggedEncodable, CborTaggedDecodable<EncryptedMessage>, UREncodable\n{\n private readonly _ciphertext: Uint8Array;\n private readonly _aad: Uint8Array;\n private readonly _nonce: Nonce;\n private readonly _auth: AuthenticationTag;\n\n private constructor(\n ciphertext: Uint8Array,\n aad: Uint8Array,\n nonce: Nonce,\n auth: AuthenticationTag,\n ) {\n this._ciphertext = new Uint8Array(ciphertext);\n this._aad = new Uint8Array(aad);\n this._nonce = nonce;\n this._auth = auth;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Restores an EncryptedMessage from its components.\n */\n static new(\n ciphertext: Uint8Array,\n aad: Uint8Array,\n nonce: Nonce,\n auth: Uint8Array | AuthenticationTag,\n ): EncryptedMessage {\n const authTag = auth instanceof AuthenticationTag ? auth : AuthenticationTag.fromData(auth);\n return new EncryptedMessage(ciphertext, aad, nonce, authTag);\n }\n\n /**\n * Create an EncryptedMessage from components (legacy alias).\n */\n static from(\n nonce: Nonce,\n ciphertext: Uint8Array,\n tag: AuthenticationTag,\n aad?: Uint8Array,\n ): EncryptedMessage {\n return new EncryptedMessage(ciphertext, aad ?? new Uint8Array(0), nonce, tag);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns a reference to the ciphertext data.\n */\n ciphertext(): Uint8Array {\n return this._ciphertext;\n }\n\n /**\n * Returns a reference to the additional authenticated data (AAD).\n */\n aad(): Uint8Array {\n return this._aad;\n }\n\n /**\n * Returns a reference to the nonce value used for encryption.\n */\n nonce(): Nonce {\n return this._nonce;\n }\n\n /**\n * Returns a reference to the authentication tag value used for encryption.\n */\n authenticationTag(): AuthenticationTag {\n return this._auth;\n }\n\n /**\n * Returns a CBOR representation in the AAD field, if it exists.\n */\n aadCbor(): Cbor | null {\n if (this._aad.length === 0) {\n return null;\n }\n try {\n return decodeCbor(this._aad);\n } catch {\n return null;\n }\n }\n\n /**\n * Returns a Digest instance if the AAD data can be parsed as CBOR.\n */\n aadDigest(): Digest | null {\n const aadCbor = this.aadCbor();\n if (aadCbor === null) {\n return null;\n }\n try {\n return Digest.fromTaggedCbor(aadCbor);\n } catch {\n return null;\n }\n }\n\n /**\n * Returns true if the AAD data can be parsed as a Digest.\n */\n hasDigest(): boolean {\n return this.aadDigest() !== null;\n }\n\n /**\n * Compare with another EncryptedMessage.\n */\n equals(other: EncryptedMessage): boolean {\n if (this._ciphertext.length !== other._ciphertext.length) return false;\n for (let i = 0; i < this._ciphertext.length; i++) {\n if (this._ciphertext[i] !== other._ciphertext[i]) return false;\n }\n if (this._aad.length !== other._aad.length) return false;\n for (let i = 0; i < this._aad.length; i++) {\n if (this._aad[i] !== other._aad[i]) return false;\n }\n return this._nonce.equals(other._nonce) && this._auth.equals(other._auth);\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `EncryptedMessage(ciphertext: ${bytesToHex(this._ciphertext).substring(0, 16)}..., nonce: ${this._nonce.toHex()}, auth: ${this._auth.toHex()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with EncryptedMessage.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_ENCRYPTED.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as an array).\n * Array format: [ciphertext, nonce, auth, ?aad]\n */\n untaggedCbor(): Cbor {\n const elements: Cbor[] = [\n toByteString(this._ciphertext),\n toByteString(this._nonce.data()),\n toByteString(this._auth.data()),\n ];\n\n if (this._aad.length > 0) {\n elements.push(toByteString(this._aad));\n }\n\n return cbor(elements);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an EncryptedMessage by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): EncryptedMessage {\n const elements = expectArray(cborValue);\n\n if (elements.length < 3) {\n throw new Error(\"EncryptedMessage must have at least 3 elements\");\n }\n\n const ciphertext = expectBytes(elements[0]);\n const nonceData = expectBytes(elements[1]);\n const nonce = Nonce.fromDataRef(nonceData);\n const authData = expectBytes(elements[2]);\n const auth = AuthenticationTag.fromDataRef(authData);\n const aad = elements.length > 3 ? expectBytes(elements[3]) : new Uint8Array(0);\n\n return EncryptedMessage.new(ciphertext, aad, nonce, auth);\n }\n\n /**\n * Creates an EncryptedMessage by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): EncryptedMessage {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): EncryptedMessage {\n // Create a dummy instance for accessing instance methods\n const dummy = new EncryptedMessage(\n new Uint8Array(0),\n new Uint8Array(0),\n Nonce.new(),\n AuthenticationTag.fromData(new Uint8Array(16)),\n );\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): EncryptedMessage {\n const cborValue = decodeCbor(data);\n return EncryptedMessage.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): EncryptedMessage {\n const cborValue = decodeCbor(data);\n const dummy = new EncryptedMessage(\n new Uint8Array(0),\n new Uint8Array(0),\n Nonce.new(),\n AuthenticationTag.fromData(new Uint8Array(16)),\n );\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the EncryptedMessage.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"encrypted\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an EncryptedMessage from a UR.\n */\n static fromUR(ur: UR): EncryptedMessage {\n ur.checkType(\"encrypted\");\n const dummy = new EncryptedMessage(\n new Uint8Array(0),\n new Uint8Array(0),\n Nonce.new(),\n AuthenticationTag.fromData(new Uint8Array(16)),\n );\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an EncryptedMessage from a UR string.\n */\n static fromURString(urString: string): EncryptedMessage {\n const ur = UR.fromURString(urString);\n return EncryptedMessage.fromUR(ur);\n }\n}\n","/**\n * Symmetric key for ChaCha20-Poly1305 AEAD encryption (32 bytes)\n *\n * A symmetric encryption key used for both encryption and decryption.\n *\n * `SymmetricKey` is a 32-byte cryptographic key used with ChaCha20-Poly1305\n * AEAD (Authenticated Encryption with Associated Data) encryption. This\n * implementation follows the IETF ChaCha20-Poly1305 specification as defined\n * in [RFC-8439](https://datatracker.ietf.org/doc/html/rfc8439).\n *\n * Symmetric encryption uses the same key for both encryption and decryption,\n * unlike asymmetric encryption where different keys are used for each\n * operation.\n *\n * # CBOR Serialization\n *\n * `SymmetricKey` is serialized to CBOR with tag 40023.\n *\n * Ported from bc-components-rust/src/symmetric/symmetric_key.rs\n */\n\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\nimport {\n aeadChaCha20Poly1305EncryptWithAad,\n aeadChaCha20Poly1305DecryptWithAad,\n} from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { SYMMETRIC_KEY as TAG_SYMMETRIC_KEY } from \"@bcts/tags\";\nimport { UR } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\nimport { Nonce } from \"../nonce.js\";\nimport { EncryptedMessage } from \"./encrypted-message.js\";\n\nconst SYMMETRIC_KEY_SIZE = 32;\n\nexport class SymmetricKey implements CborTaggedEncodable, CborTaggedDecodable<SymmetricKey> {\n static readonly SYMMETRIC_KEY_SIZE = SYMMETRIC_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== SYMMETRIC_KEY_SIZE) {\n throw CryptoError.invalidSize(SYMMETRIC_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new random symmetric key.\n */\n static new(): SymmetricKey {\n return SymmetricKey.random();\n }\n\n /**\n * Create a new symmetric key from data.\n */\n static fromData(data: Uint8Array): SymmetricKey {\n return new SymmetricKey(new Uint8Array(data));\n }\n\n /**\n * Create a new symmetric key from data (validates length).\n */\n static fromDataRef(data: Uint8Array): SymmetricKey {\n if (data.length !== SYMMETRIC_KEY_SIZE) {\n throw CryptoError.invalidSize(SYMMETRIC_KEY_SIZE, data.length);\n }\n return SymmetricKey.fromData(data);\n }\n\n /**\n * Create a SymmetricKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): SymmetricKey {\n return SymmetricKey.fromData(data);\n }\n\n /**\n * Create a SymmetricKey from hex string.\n */\n static fromHex(hex: string): SymmetricKey {\n return SymmetricKey.fromData(hexToBytes(hex));\n }\n\n /**\n * Generate a random symmetric key.\n */\n static random(): SymmetricKey {\n const rng = new SecureRandomNumberGenerator();\n return SymmetricKey.randomUsing(rng);\n }\n\n /**\n * Generate a random symmetric key using provided RNG.\n */\n static randomUsing(rng: SecureRandomNumberGenerator): SymmetricKey {\n return new SymmetricKey(rng.randomData(SYMMETRIC_KEY_SIZE));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get the data of the symmetric key.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the data of the symmetric key as a byte slice.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get a copy of the raw key bytes.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Compare with another SymmetricKey.\n */\n equals(other: SymmetricKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `SymmetricKey(${this.hex().substring(0, 8)}...)`;\n }\n\n // ============================================================================\n // Encryption/Decryption\n // ============================================================================\n\n /**\n * Encrypt the given plaintext with this key, and the given additional\n * authenticated data and nonce.\n */\n encrypt(plaintext: Uint8Array, aad?: Uint8Array, nonce?: Nonce): EncryptedMessage {\n const effectiveNonce = nonce ?? Nonce.new();\n const effectiveAad = aad ?? new Uint8Array(0);\n\n const [ciphertext, authTag] = aeadChaCha20Poly1305EncryptWithAad(\n plaintext,\n this._data,\n effectiveNonce.data(),\n effectiveAad,\n );\n\n return EncryptedMessage.new(ciphertext, effectiveAad, effectiveNonce, authTag);\n }\n\n /**\n * Decrypt the given encrypted message with this key.\n */\n decrypt(message: EncryptedMessage): Uint8Array {\n return aeadChaCha20Poly1305DecryptWithAad(\n message.ciphertext(),\n this._data,\n message.nonce().data(),\n message.aad(),\n message.authenticationTag().data(),\n );\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with SymmetricKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SYMMETRIC_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a SymmetricKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): SymmetricKey {\n const data = expectBytes(cbor);\n return SymmetricKey.fromDataRef(data);\n }\n\n /**\n * Creates a SymmetricKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): SymmetricKey {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): SymmetricKey {\n const instance = new SymmetricKey(new Uint8Array(SYMMETRIC_KEY_SIZE));\n return instance.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): SymmetricKey {\n const cbor = decodeCbor(data);\n return SymmetricKey.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): SymmetricKey {\n const cbor = decodeCbor(data);\n const bytes = expectBytes(cbor);\n return SymmetricKey.fromDataRef(bytes);\n }\n\n // ============================================================================\n // UR (Uniform Resource) Serialization\n // ============================================================================\n\n /**\n * Get the UR type for symmetric keys.\n */\n static readonly UR_TYPE = \"crypto-key\";\n\n /**\n * Returns the UR representation of the symmetric key.\n */\n ur(): UR {\n return UR.new(SymmetricKey.UR_TYPE, this.taggedCbor());\n }\n\n /**\n * Returns the UR string representation of the symmetric key.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a SymmetricKey from a UR.\n */\n static fromUR(ur: UR): SymmetricKey {\n ur.checkType(SymmetricKey.UR_TYPE);\n return SymmetricKey.fromTaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a SymmetricKey from a UR string.\n */\n static fromURString(urString: string): SymmetricKey {\n const ur = UR.fromURString(urString);\n return SymmetricKey.fromUR(ur);\n }\n\n /**\n * Alias for fromURString for Rust API compatibility.\n */\n static fromUrString(urString: string): SymmetricKey {\n return SymmetricKey.fromURString(urString);\n }\n}\n","/**\n * X25519 private key for ECDH key exchange (32 bytes seed)\n *\n * X25519 is an elliptic-curve Diffie-Hellman key exchange protocol based on\n * Curve25519 as defined in RFC 7748. It allows two parties to establish a\n * shared secret key over an insecure channel.\n *\n * Key features of X25519:\n * - High security (128-bit security level)\n * - High performance\n * - Small key sizes (32 bytes)\n * - Protection against various side-channel attacks\n *\n * # CBOR Serialization\n *\n * `X25519PrivateKey` is serialized to CBOR with tag 40010.\n *\n * ```\n * #6.40010(h'<32-byte-private-key>')\n * ```\n *\n * Ported from bc-components-rust/src/x25519/x25519_private_key.rs\n */\n\nimport { SecureRandomNumberGenerator, type RandomNumberGenerator } from \"@bcts/rand\";\nimport {\n X25519_PRIVATE_KEY_SIZE,\n x25519PublicKeyFromPrivateKey,\n x25519SharedKey,\n deriveAgreementPrivateKey,\n} from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { X25519_PRIVATE_KEY as TAG_X25519_PRIVATE_KEY } from \"@bcts/tags\";\nimport { CryptoError } from \"../error.js\";\nimport { X25519PublicKey } from \"./x25519-public-key.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\n\nexport class X25519PrivateKey\n implements CborTaggedEncodable, CborTaggedDecodable<X25519PrivateKey>, UREncodable\n{\n static readonly KEY_SIZE = X25519_PRIVATE_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n private _publicKey?: X25519PublicKey;\n\n private constructor(data: Uint8Array) {\n if (data.length !== X25519_PRIVATE_KEY_SIZE) {\n throw CryptoError.invalidSize(X25519_PRIVATE_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Generate a new random X25519PrivateKey.\n */\n static new(): X25519PrivateKey {\n return X25519PrivateKey.random();\n }\n\n /**\n * Generate a new random X25519PrivateKey.\n */\n static random(): X25519PrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return X25519PrivateKey.newUsing(rng);\n }\n\n /**\n * Generate a new random X25519PrivateKey using provided RNG.\n */\n static newUsing(rng: RandomNumberGenerator): X25519PrivateKey {\n return new X25519PrivateKey(rng.randomData(X25519_PRIVATE_KEY_SIZE));\n }\n\n /**\n * Generate a new random X25519PrivateKey and corresponding X25519PublicKey.\n */\n static keypair(): [X25519PrivateKey, X25519PublicKey] {\n const privateKey = X25519PrivateKey.new();\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Generate a new random X25519PrivateKey and corresponding X25519PublicKey\n * using the given random number generator.\n */\n static keypairUsing(rng: RandomNumberGenerator): [X25519PrivateKey, X25519PublicKey] {\n const privateKey = X25519PrivateKey.newUsing(rng);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Derive an X25519PrivateKey from the given key material.\n *\n * @param keyMaterial - The key material to derive from\n * @returns A new X25519PrivateKey derived from the key material\n */\n static deriveFromKeyMaterial(keyMaterial: Uint8Array): X25519PrivateKey {\n return new X25519PrivateKey(deriveAgreementPrivateKey(keyMaterial));\n }\n\n /**\n * Restore an X25519PrivateKey from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): X25519PrivateKey {\n return new X25519PrivateKey(new Uint8Array(data));\n }\n\n /**\n * Restore an X25519PrivateKey from a reference to an array of bytes.\n * Validates the length.\n */\n static fromDataRef(data: Uint8Array): X25519PrivateKey {\n if (data.length !== X25519_PRIVATE_KEY_SIZE) {\n throw CryptoError.invalidSize(X25519_PRIVATE_KEY_SIZE, data.length);\n }\n return X25519PrivateKey.fromData(data);\n }\n\n /**\n * Create an X25519PrivateKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): X25519PrivateKey {\n return X25519PrivateKey.fromData(data);\n }\n\n /**\n * Restore an X25519PrivateKey from a hex string.\n */\n static fromHex(hex: string): X25519PrivateKey {\n return X25519PrivateKey.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw private key bytes (copy).\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Get the X25519PublicKey corresponding to this X25519PrivateKey.\n */\n publicKey(): X25519PublicKey {\n if (this._publicKey === undefined) {\n const publicKeyBytes = x25519PublicKeyFromPrivateKey(this._data);\n this._publicKey = X25519PublicKey.fromData(publicKeyBytes);\n }\n return this._publicKey;\n }\n\n /**\n * Derive a shared symmetric key from this X25519PrivateKey and the given\n * X25519PublicKey.\n *\n * @param publicKey - The other party's public key\n * @returns A SymmetricKey derived from the shared secret\n */\n sharedKeyWith(publicKey: X25519PublicKey): SymmetricKey {\n const shared = x25519SharedKey(this._data, publicKey.data());\n return SymmetricKey.fromData(shared);\n }\n\n /**\n * Perform ECDH key agreement with a public key (legacy method).\n *\n * @deprecated Use sharedKeyWith() instead which returns a SymmetricKey\n */\n sharedSecret(publicKey: X25519PublicKey): Uint8Array {\n try {\n const shared = x25519SharedKey(this._data, publicKey.data());\n return new Uint8Array(shared);\n } catch (e: unknown) {\n throw CryptoError.cryptoOperation(`ECDH key agreement failed: ${String(e)}`);\n }\n }\n\n /**\n * Compare with another X25519PrivateKey.\n */\n equals(other: X25519PrivateKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `X25519PrivateKey(${this.toHex().substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with X25519PrivateKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_X25519_PRIVATE_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an X25519PrivateKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): X25519PrivateKey {\n const data = expectBytes(cbor);\n return X25519PrivateKey.fromDataRef(data);\n }\n\n /**\n * Creates an X25519PrivateKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): X25519PrivateKey {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): X25519PrivateKey {\n const dummy = new X25519PrivateKey(new Uint8Array(X25519_PRIVATE_KEY_SIZE));\n return dummy.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): X25519PrivateKey {\n const cbor = decodeCbor(data);\n return X25519PrivateKey.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): X25519PrivateKey {\n const cbor = decodeCbor(data);\n const dummy = new X25519PrivateKey(new Uint8Array(X25519_PRIVATE_KEY_SIZE));\n return dummy.fromUntaggedCbor(cbor);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the X25519PrivateKey.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n const name = TAG_X25519_PRIVATE_KEY.name;\n if (name === undefined) {\n throw new Error(\"X25519_PRIVATE_KEY tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an X25519PrivateKey from a UR.\n */\n static fromUR(ur: UR): X25519PrivateKey {\n const name = TAG_X25519_PRIVATE_KEY.name;\n if (name === undefined) {\n throw new Error(\"X25519_PRIVATE_KEY tag name is undefined\");\n }\n ur.checkType(name);\n const dummy = new X25519PrivateKey(new Uint8Array(X25519_PRIVATE_KEY_SIZE));\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an X25519PrivateKey from a UR string.\n */\n static fromURString(urString: string): X25519PrivateKey {\n const ur = UR.fromURString(urString);\n return X25519PrivateKey.fromUR(ur);\n }\n}\n","/**\n * Ed25519 public key for EdDSA signature verification (32 bytes)\n * Ported from bc-components-rust/src/ed25519_public_key.rs\n */\n\nimport { ED25519_PUBLIC_KEY_SIZE, ED25519_SIGNATURE_SIZE, ed25519Verify } from \"@bcts/crypto\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\n\nexport class Ed25519PublicKey {\n private readonly data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== ED25519_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(ED25519_PUBLIC_KEY_SIZE, data.length);\n }\n this.data = new Uint8Array(data);\n }\n\n /**\n * Create an Ed25519PublicKey from raw bytes\n */\n static from(data: Uint8Array): Ed25519PublicKey {\n return new Ed25519PublicKey(new Uint8Array(data));\n }\n\n /**\n * Create an Ed25519PublicKey from hex string\n */\n static fromHex(hex: string): Ed25519PublicKey {\n return new Ed25519PublicKey(hexToBytes(hex));\n }\n\n /**\n * Get the raw public key bytes\n */\n toData(): Uint8Array {\n return new Uint8Array(this.data);\n }\n\n /**\n * Get hex string representation\n */\n toHex(): string {\n return bytesToHex(this.data);\n }\n\n /**\n * Get base64 representation\n */\n toBase64(): string {\n return toBase64(this.data);\n }\n\n /**\n * Verify a signature using Ed25519\n */\n verify(message: Uint8Array, signature: Uint8Array): boolean {\n try {\n if (signature.length !== ED25519_SIGNATURE_SIZE) {\n throw CryptoError.invalidSize(ED25519_SIGNATURE_SIZE, signature.length);\n }\n return ed25519Verify(this.data, message, signature);\n } catch (e) {\n throw CryptoError.cryptoOperation(`Ed25519 verification failed: ${String(e)}`);\n }\n }\n\n /**\n * Compare with another Ed25519PublicKey\n */\n equals(other: Ed25519PublicKey): boolean {\n if (this.data.length !== other.data.length) return false;\n for (let i = 0; i < this.data.length; i++) {\n if (this.data[i] !== other.data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation\n */\n toString(): string {\n return `Ed25519PublicKey(${this.toHex().substring(0, 16)}...)`;\n }\n}\n","/**\n * Ed25519 private key for EdDSA signatures (32 bytes seed)\n * Ported from bc-components-rust/src/ed25519_private_key.rs\n */\n\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\nimport {\n ED25519_PRIVATE_KEY_SIZE,\n ed25519PublicKeyFromPrivateKey,\n ed25519Sign,\n} from \"@bcts/crypto\";\nimport { CryptoError } from \"../error.js\";\nimport { Ed25519PublicKey } from \"./ed25519-public-key.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\n\nexport class Ed25519PrivateKey {\n private readonly seed: Uint8Array;\n private _publicKey?: Ed25519PublicKey;\n\n private constructor(seed: Uint8Array) {\n if (seed.length !== ED25519_PRIVATE_KEY_SIZE) {\n throw CryptoError.invalidSize(ED25519_PRIVATE_KEY_SIZE, seed.length);\n }\n this.seed = new Uint8Array(seed);\n }\n\n /**\n * Create an Ed25519PrivateKey from seed (32 bytes)\n */\n static from(seed: Uint8Array): Ed25519PrivateKey {\n return new Ed25519PrivateKey(new Uint8Array(seed));\n }\n\n /**\n * Create an Ed25519PrivateKey from hex string (64 hex characters)\n */\n static fromHex(hex: string): Ed25519PrivateKey {\n return new Ed25519PrivateKey(hexToBytes(hex));\n }\n\n /**\n * Generate a random Ed25519PrivateKey\n */\n static random(): Ed25519PrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return new Ed25519PrivateKey(rng.randomData(ED25519_PRIVATE_KEY_SIZE));\n }\n\n /**\n * Generate a random Ed25519PrivateKey using provided RNG\n */\n static randomUsing(rng: SecureRandomNumberGenerator): Ed25519PrivateKey {\n return new Ed25519PrivateKey(rng.randomData(ED25519_PRIVATE_KEY_SIZE));\n }\n\n /**\n * Get the raw seed bytes (32 bytes)\n */\n toData(): Uint8Array {\n return new Uint8Array(this.seed);\n }\n\n /**\n * Get hex string representation of the seed\n */\n toHex(): string {\n return bytesToHex(this.seed);\n }\n\n /**\n * Get base64 representation of the seed\n */\n toBase64(): string {\n return toBase64(this.seed);\n }\n\n /**\n * Derive the corresponding public key\n */\n publicKey(): Ed25519PublicKey {\n if (this._publicKey === undefined) {\n const publicKeyBytes = ed25519PublicKeyFromPrivateKey(this.seed);\n this._publicKey = Ed25519PublicKey.from(publicKeyBytes);\n }\n return this._publicKey;\n }\n\n /**\n * Sign a message using Ed25519\n */\n sign(message: Uint8Array): Uint8Array {\n try {\n const signature = ed25519Sign(this.seed, message);\n return new Uint8Array(signature);\n } catch (e) {\n throw CryptoError.cryptoOperation(`Ed25519 signing failed: ${String(e)}`);\n }\n }\n\n /**\n * Compare with another Ed25519PrivateKey\n */\n equals(other: Ed25519PrivateKey): boolean {\n if (this.seed.length !== other.seed.length) return false;\n for (let i = 0; i < this.seed.length; i++) {\n if (this.seed[i] !== other.seed[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation\n */\n toString(): string {\n return `Ed25519PrivateKey(${this.toHex().substring(0, 16)}...)`;\n }\n}\n","/**\n * Sr25519PublicKey - Public key for Schnorr signatures over Ristretto25519\n *\n * SR25519 is the signature scheme used by Polkadot/Substrate.\n * It is based on Schnorr signatures over the Ristretto group.\n *\n * Note: SR25519 uses the SigningPublicKey CBOR tag (40022) with discriminator 3.\n *\n * Ported from bc-components-rust/src/sr25519/sr25519_public_key.rs\n */\n\nimport * as sr25519 from \"@scure/sr25519\";\nimport { SR25519_PUBLIC_KEY_SIZE, SR25519_DEFAULT_CONTEXT } from \"./sr25519-private-key.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * Sr25519PublicKey - Public key for Schnorr signatures over Ristretto25519.\n *\n * This is the signature scheme used by Polkadot/Substrate.\n */\nexport class Sr25519PublicKey {\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== SR25519_PUBLIC_KEY_SIZE) {\n throw new Error(\n `Sr25519PublicKey must be ${SR25519_PUBLIC_KEY_SIZE} bytes, got ${data.length}`,\n );\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an Sr25519 public key from raw bytes.\n */\n static from(data: Uint8Array): Sr25519PublicKey {\n return new Sr25519PublicKey(data);\n }\n\n /**\n * Create an Sr25519 public key from a hex string.\n */\n static fromHex(hex: string): Sr25519PublicKey {\n const matches = hex.match(/.{1,2}/g);\n if (matches === null) {\n throw new Error(\"Invalid hex string\");\n }\n const data = new Uint8Array(matches.map((byte) => parseInt(byte, 16)));\n return Sr25519PublicKey.from(data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the raw key bytes.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the raw key bytes (alias for toData).\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns the hex representation of the key.\n */\n toHex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Verify a signature using the default \"substrate\" context.\n *\n * @param signature - The 64-byte signature\n * @param message - The message that was signed\n * @returns true if the signature is valid\n */\n verify(signature: Uint8Array, message: Uint8Array): boolean {\n return this.verifyWithContext(signature, message, SR25519_DEFAULT_CONTEXT);\n }\n\n /**\n * Verify a signature using a custom context.\n *\n * Note: The @scure/sr25519 library uses a hardcoded \"substrate\" context.\n * Custom context is accepted for API compatibility but only signatures created\n * with \"substrate\" context will verify correctly.\n *\n * @param signature - The 64-byte signature\n * @param message - The message that was signed\n * @param _context - The signing context (only \"substrate\" is supported)\n * @returns true if the signature is valid\n */\n verifyWithContext(signature: Uint8Array, message: Uint8Array, _context: Uint8Array): boolean {\n try {\n // Note: @scure/sr25519 verify() uses hardcoded \"substrate\" context\n // Arguments: verify(message, signature, publicKey)\n return sr25519.verify(message, signature, this._data);\n } catch {\n return false;\n }\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another Sr25519PublicKey.\n */\n equals(other: Sr25519PublicKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `Sr25519PublicKey(${hex.substring(0, 16)}...)`;\n }\n}\n","/**\n * Sr25519PrivateKey - Schnorr signatures over Ristretto25519\n *\n * SR25519 is the signature scheme used by Polkadot/Substrate.\n * It is based on Schnorr signatures over the Ristretto group.\n *\n * Key sizes:\n * - Private key (seed): 32 bytes\n * - Public key: 32 bytes\n * - Signature: 64 bytes\n *\n * Note: SR25519 uses the SigningPrivateKey CBOR tag (40021) with discriminator 3.\n *\n * Ported from bc-components-rust/src/sr25519/sr25519_private_key.rs\n */\n\nimport * as sr25519 from \"@scure/sr25519\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\nimport { blake2b } from \"@noble/hashes/blake2.js\";\nimport { Sr25519PublicKey } from \"./sr25519-public-key.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/** Size of SR25519 private key (seed) in bytes */\nexport const SR25519_PRIVATE_KEY_SIZE = 32;\n\n/** Size of SR25519 public key in bytes */\nexport const SR25519_PUBLIC_KEY_SIZE = 32;\n\n/** Size of SR25519 signature in bytes */\nexport const SR25519_SIGNATURE_SIZE = 64;\n\n/** Default signing context (Substrate/Polkadot compatible) */\nexport const SR25519_DEFAULT_CONTEXT = new TextEncoder().encode(\"substrate\");\n\n/**\n * Sr25519PrivateKey - Private key for Schnorr signatures over Ristretto25519.\n *\n * This is the signature scheme used by Polkadot/Substrate.\n */\nexport class Sr25519PrivateKey {\n private readonly _seed: Uint8Array;\n private _cachedPublicKey?: Sr25519PublicKey;\n\n private constructor(seed: Uint8Array) {\n if (seed.length !== SR25519_PRIVATE_KEY_SIZE) {\n throw new Error(\n `Sr25519PrivateKey seed must be ${SR25519_PRIVATE_KEY_SIZE} bytes, got ${seed.length}`,\n );\n }\n this._seed = new Uint8Array(seed);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new random Sr25519 private key.\n */\n static random(): Sr25519PrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return Sr25519PrivateKey.randomUsing(rng);\n }\n\n /**\n * Create a new random Sr25519 private key using the provided RNG.\n */\n static randomUsing(rng: RandomNumberGenerator): Sr25519PrivateKey {\n const seed = rng.randomData(SR25519_PRIVATE_KEY_SIZE);\n return new Sr25519PrivateKey(seed);\n }\n\n /**\n * Create an Sr25519 private key from a 32-byte seed.\n */\n static fromSeed(seed: Uint8Array): Sr25519PrivateKey {\n return new Sr25519PrivateKey(seed);\n }\n\n /**\n * Create an Sr25519 private key from raw data.\n * Alias for fromSeed.\n */\n static from(data: Uint8Array): Sr25519PrivateKey {\n return Sr25519PrivateKey.fromSeed(data);\n }\n\n /**\n * Create an Sr25519 private key from a hex string.\n */\n static fromHex(hex: string): Sr25519PrivateKey {\n const matches = hex.match(/.{1,2}/g);\n if (matches === null) {\n throw new Error(\"Invalid hex string\");\n }\n const data = new Uint8Array(matches.map((byte) => parseInt(byte, 16)));\n return Sr25519PrivateKey.fromSeed(data);\n }\n\n /**\n * Derive an Sr25519 private key from arbitrary key material using BLAKE2b.\n *\n * @param keyMaterial - Arbitrary bytes to derive the key from\n * @returns A new Sr25519 private key\n */\n static deriveFromKeyMaterial(keyMaterial: Uint8Array): Sr25519PrivateKey {\n // Use BLAKE2b to derive a 32-byte seed from arbitrary key material\n const seed = blake2b(keyMaterial, { dkLen: SR25519_PRIVATE_KEY_SIZE });\n return new Sr25519PrivateKey(seed);\n }\n\n /**\n * Generate a keypair and return both private and public keys.\n *\n * @returns Tuple of [privateKey, publicKey]\n */\n static keypair(): [Sr25519PrivateKey, Sr25519PublicKey] {\n const privateKey = Sr25519PrivateKey.random();\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Generate a keypair using the provided RNG.\n *\n * @param rng - Random number generator\n * @returns Tuple of [privateKey, publicKey]\n */\n static keypairUsing(rng: RandomNumberGenerator): [Sr25519PrivateKey, Sr25519PublicKey] {\n const privateKey = Sr25519PrivateKey.randomUsing(rng);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the raw seed bytes.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._seed);\n }\n\n /**\n * Returns the raw seed bytes (alias for toData).\n */\n asBytes(): Uint8Array {\n return this._seed;\n }\n\n /**\n * Returns the hex representation of the seed.\n */\n toHex(): string {\n return bytesToHex(this._seed);\n }\n\n /**\n * Derives the corresponding public key.\n */\n publicKey(): Sr25519PublicKey {\n if (this._cachedPublicKey === undefined) {\n const secretKey = sr25519.secretFromSeed(this._seed);\n const pubKeyBytes = sr25519.getPublicKey(secretKey);\n this._cachedPublicKey = Sr25519PublicKey.from(pubKeyBytes);\n }\n return this._cachedPublicKey;\n }\n\n /**\n * Sign a message using the default \"substrate\" context.\n *\n * @param message - The message to sign\n * @returns 64-byte signature\n */\n sign(message: Uint8Array): Uint8Array {\n return this.signWithContext(message, SR25519_DEFAULT_CONTEXT);\n }\n\n /**\n * Sign a message using a custom context.\n *\n * Note: The @scure/sr25519 library uses a hardcoded \"substrate\" context.\n * Custom context is accepted for API compatibility but only \"substrate\" context\n * will produce signatures verifiable by this library.\n *\n * @param message - The message to sign\n * @param _context - The signing context (only \"substrate\" is supported)\n * @returns 64-byte signature\n */\n signWithContext(message: Uint8Array, _context: Uint8Array): Uint8Array {\n const secretKey = sr25519.secretFromSeed(this._seed);\n // Note: @scure/sr25519 sign() uses hardcoded \"substrate\" context\n // Arguments: sign(secretKey, message, random?)\n return sr25519.sign(secretKey, message);\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another Sr25519PrivateKey.\n */\n equals(other: Sr25519PrivateKey): boolean {\n if (this._seed.length !== other._seed.length) return false;\n for (let i = 0; i < this._seed.length; i++) {\n if (this._seed[i] !== other._seed[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation (truncated for security).\n */\n toString(): string {\n const hex = bytesToHex(this._seed);\n return `Sr25519PrivateKey(${hex.substring(0, 8)}...)`;\n }\n}\n","/**\n * Base traits for elliptic curve keys\n *\n * This module defines the base interfaces for all elliptic curve keys,\n * matching the Rust trait hierarchy:\n * - `ECKeyBase` - Base trait for all EC keys (data, hex, fromHex, fromDataRef)\n * - `ECKey` - Keys that can derive a public key (publicKey)\n * - `ECPublicKeyBase` - Public keys that can provide uncompressed form\n *\n * Ported from bc-components-rust/src/ec_key/ec_key_base.rs\n * and bc-components-rust/src/ec_key/ec_public_key_base.rs\n */\n\nimport type { ECPublicKey } from \"./ec-public-key.js\";\nimport type { ECUncompressedPublicKey } from \"./ec-uncompressed-public-key.js\";\n\n/**\n * A base interface for all elliptic curve keys.\n *\n * This interface defines common functionality for all elliptic curve keys,\n * including both private and public keys. It provides methods for key\n * construction from binary data and hexadecimal strings, as well as conversion\n * to hexadecimal format.\n *\n * All EC key types have a fixed size depending on their specific type:\n * - EC private keys: 32 bytes\n * - EC compressed public keys: 33 bytes\n * - EC uncompressed public keys: 65 bytes\n * - Schnorr public keys: 32 bytes\n */\nexport interface ECKeyBase {\n /**\n * Returns the key's binary data.\n */\n data(): Uint8Array;\n\n /**\n * Returns the key as a hexadecimal string.\n */\n hex(): string;\n}\n\n/**\n * Type guard to check if an object implements ECKeyBase.\n */\nexport function isECKeyBase(obj: unknown): obj is ECKeyBase {\n if (obj === null || typeof obj !== \"object\") return false;\n const candidate = obj as ECKeyBase;\n return typeof candidate.data === \"function\" && typeof candidate.hex === \"function\";\n}\n\n/**\n * An interface for elliptic curve keys that can derive a public key.\n *\n * This interface extends `ECKeyBase` to provide a method for deriving\n * the corresponding compressed public key. It is implemented by both\n * private keys (where it generates the public key) and public keys\n * (where it may return self or convert between formats).\n */\nexport interface ECKey extends ECKeyBase {\n /**\n * Returns the compressed public key corresponding to this key.\n */\n publicKey(): ECPublicKey;\n}\n\n/**\n * Type guard to check if an object implements ECKey.\n */\nexport function isECKey(obj: unknown): obj is ECKey {\n if (!isECKeyBase(obj)) return false;\n const candidate = obj as ECKey;\n return typeof candidate.publicKey === \"function\";\n}\n\n/**\n * An interface for elliptic curve public keys that can provide their\n * uncompressed form.\n *\n * This interface extends `ECKey` to provide a method for obtaining the\n * uncompressed representation of a public key. Elliptic curve public keys can\n * be represented in both compressed (33 bytes) and uncompressed (65 bytes)\n * formats:\n *\n * - Compressed format: Uses a single byte prefix (0x02 or 0x03) followed by\n * the x-coordinate (32 bytes), with the prefix indicating the parity of the\n * y-coordinate.\n *\n * - Uncompressed format: Uses a byte prefix (0x04) followed by both x and y\n * coordinates (32 bytes each), for a total of 65 bytes.\n *\n * The compressed format is more space-efficient and is recommended for most\n * applications, but some legacy systems require the uncompressed format.\n */\nexport interface ECPublicKeyBase extends ECKey {\n /**\n * Returns the uncompressed public key representation.\n */\n uncompressedPublicKey(): ECUncompressedPublicKey;\n}\n\n/**\n * Type guard to check if an object implements ECPublicKeyBase.\n */\nexport function isECPublicKeyBase(obj: unknown): obj is ECPublicKeyBase {\n if (!isECKey(obj)) return false;\n const candidate = obj as ECPublicKeyBase;\n return typeof candidate.uncompressedPublicKey === \"function\";\n}\n","/**\n * EC uncompressed public key for ECDSA (secp256k1, 65 bytes)\n *\n * An `ECUncompressedPublicKey` is a 65-byte uncompressed representation of a\n * public key on the secp256k1 curve. The first byte is 0x04 (uncompressed prefix),\n * followed by the 32-byte x-coordinate and 32-byte y-coordinate.\n *\n * While compressed public keys (33 bytes) are preferred for space efficiency,\n * uncompressed keys are sometimes needed for compatibility with legacy systems.\n *\n * # CBOR Serialization\n *\n * `ECUncompressedPublicKey` is serialized to CBOR with tags 40306 (or legacy 306).\n *\n * The format is a map:\n * ```\n * #6.40306({\n * 3: h'<65-byte-uncompressed-public-key>' // key data\n * })\n * ```\n *\n * Ported from bc-components-rust/src/ec_key/ec_uncompressed_public_key.rs\n */\n\nimport { ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE, ecdsaCompressPublicKey } from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectMap,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { EC_KEY as TAG_EC_KEY, EC_KEY_V1 as TAG_EC_KEY_V1 } from \"@bcts/tags\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\nimport type { ECKeyBase } from \"./ec-key-base.js\";\n\nexport class ECUncompressedPublicKey\n implements\n ECKeyBase,\n CborTaggedEncodable,\n CborTaggedDecodable<ECUncompressedPublicKey>,\n UREncodable\n{\n static readonly KEY_SIZE = ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Restore an ECUncompressedPublicKey from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): ECUncompressedPublicKey {\n return new ECUncompressedPublicKey(new Uint8Array(data));\n }\n\n /**\n * Restore an ECUncompressedPublicKey from a reference to an array of bytes.\n * Validates the length.\n */\n static fromDataRef(data: Uint8Array): ECUncompressedPublicKey {\n if (data.length !== ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE, data.length);\n }\n return ECUncompressedPublicKey.fromData(data);\n }\n\n /**\n * Create an ECUncompressedPublicKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): ECUncompressedPublicKey {\n return ECUncompressedPublicKey.fromData(data);\n }\n\n /**\n * Restore an ECUncompressedPublicKey from a hex string.\n */\n static fromHex(hex: string): ECUncompressedPublicKey {\n return ECUncompressedPublicKey.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw public key bytes (copy).\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Convert to compressed public key format.\n * Note: Returns the compressed bytes. To get ECPublicKey, use the ec-public-key module.\n */\n compressedData(): Uint8Array {\n return ecdsaCompressPublicKey(this._data);\n }\n\n /**\n * Compare with another ECUncompressedPublicKey.\n */\n equals(other: ECUncompressedPublicKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `ECUncompressedPublicKey(${this.toHex().substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with ECUncompressedPublicKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_EC_KEY.value, TAG_EC_KEY_V1.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: { 3: h'<65-byte-key>' }\n */\n untaggedCbor(): Cbor {\n const map = new Map<number, unknown>();\n map.set(3, toByteString(this._data));\n return cbor(map);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an ECUncompressedPublicKey by decoding it from untagged CBOR.\n *\n * Format: { 3: h'<65-byte-key>' }\n */\n fromUntaggedCbor(cborValue: Cbor): ECUncompressedPublicKey {\n const map = expectMap(cborValue);\n\n // Check that key 2 is not present (would indicate private key)\n const isPrivate = map.get<number, boolean>(2);\n if (isPrivate === true) {\n throw new Error(\"Expected ECUncompressedPublicKey but found private key\");\n }\n\n // Get key data from key 3\n // CborMap.extract() returns native types (Uint8Array for byte strings)\n const keyData = map.extract<number, Uint8Array>(3);\n if (keyData === undefined || keyData.length === 0) {\n throw new Error(\"ECUncompressedPublicKey CBOR must have key 3 (data)\");\n }\n\n return ECUncompressedPublicKey.fromDataRef(keyData);\n }\n\n /**\n * Creates an ECUncompressedPublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): ECUncompressedPublicKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): ECUncompressedPublicKey {\n const dummy = new ECUncompressedPublicKey(new Uint8Array(ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE));\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): ECUncompressedPublicKey {\n const cborValue = decodeCbor(data);\n return ECUncompressedPublicKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): ECUncompressedPublicKey {\n const cborValue = decodeCbor(data);\n const dummy = new ECUncompressedPublicKey(new Uint8Array(ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE));\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the ECUncompressedPublicKey.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n const name = TAG_EC_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_EC_KEY.name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an ECUncompressedPublicKey from a UR.\n */\n static fromUR(ur: UR): ECUncompressedPublicKey {\n const name = TAG_EC_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_EC_KEY.name is undefined\");\n }\n ur.checkType(name);\n const dummy = new ECUncompressedPublicKey(new Uint8Array(ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE));\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an ECUncompressedPublicKey from a UR string.\n */\n static fromURString(urString: string): ECUncompressedPublicKey {\n const ur = UR.fromURString(urString);\n return ECUncompressedPublicKey.fromUR(ur);\n }\n}\n","/**\n * EC compressed public key for ECDSA verification (secp256k1, 33 bytes)\n *\n * An `ECPublicKey` is a 33-byte compressed representation of a public key on\n * the secp256k1 curve. The first byte is a prefix (0x02 or 0x03) that\n * indicates the parity of the y-coordinate, followed by the 32-byte\n * x-coordinate.\n *\n * These public keys are used to:\n * - Verify ECDSA signatures\n * - Identify the owner of a private key without revealing the private key\n *\n * # CBOR Serialization\n *\n * `ECPublicKey` is serialized to CBOR with tags 40306 (or legacy 306).\n *\n * The format is a map:\n * ```\n * #6.40306({\n * 3: h'<33-byte-public-key>' // key data (no key 2 means public key)\n * })\n * ```\n *\n * Ported from bc-components-rust/src/ec_key/ec_public_key.rs\n */\n\nimport { ECDSA_PUBLIC_KEY_SIZE, ecdsaVerify, ecdsaDecompressPublicKey } from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectMap,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { EC_KEY as TAG_EC_KEY, EC_KEY_V1 as TAG_EC_KEY_V1 } from \"@bcts/tags\";\nimport { CryptoError } from \"../error.js\";\nimport { ECUncompressedPublicKey } from \"./ec-uncompressed-public-key.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\nimport type { ECPublicKeyBase } from \"./ec-key-base.js\";\n\nexport class ECPublicKey\n implements ECPublicKeyBase, CborTaggedEncodable, CborTaggedDecodable<ECPublicKey>, UREncodable\n{\n static readonly KEY_SIZE = ECDSA_PUBLIC_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== ECDSA_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(ECDSA_PUBLIC_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Restore an ECPublicKey from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): ECPublicKey {\n return new ECPublicKey(new Uint8Array(data));\n }\n\n /**\n * Restore an ECPublicKey from a reference to an array of bytes.\n * Validates the length.\n */\n static fromDataRef(data: Uint8Array): ECPublicKey {\n if (data.length !== ECDSA_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(ECDSA_PUBLIC_KEY_SIZE, data.length);\n }\n return ECPublicKey.fromData(data);\n }\n\n /**\n * Create an ECPublicKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): ECPublicKey {\n return ECPublicKey.fromData(data);\n }\n\n /**\n * Restore an ECPublicKey from a hex string.\n */\n static fromHex(hex: string): ECPublicKey {\n return ECPublicKey.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw public key bytes (copy).\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Returns the compressed public key (self).\n *\n * This method implements the ECKey interface. Since ECPublicKey is already\n * a compressed public key, this returns itself.\n */\n publicKey(): ECPublicKey {\n return this;\n }\n\n /**\n * Convert this compressed public key to uncompressed format.\n */\n uncompressedPublicKey(): ECUncompressedPublicKey {\n const uncompressed = ecdsaDecompressPublicKey(this._data);\n return ECUncompressedPublicKey.fromData(uncompressed);\n }\n\n /**\n * Verify an ECDSA signature.\n *\n * @param signature - The 64-byte signature to verify\n * @param message - The message that was signed\n * @returns true if the signature is valid\n */\n verify(signature: Uint8Array, message: Uint8Array): boolean {\n try {\n return ecdsaVerify(this._data, signature, message);\n } catch {\n return false;\n }\n }\n\n /**\n * Compare with another ECPublicKey.\n */\n equals(other: ECPublicKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `ECPublicKey(${this.toHex().substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with ECPublicKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_EC_KEY.value, TAG_EC_KEY_V1.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: { 3: h'<33-byte-key>' }\n * Note: No key 2 indicates this is a public key\n */\n untaggedCbor(): Cbor {\n const map = new Map<number, unknown>();\n map.set(3, toByteString(this._data));\n return cbor(map);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an ECPublicKey by decoding it from untagged CBOR.\n *\n * Format: { 3: h'<33-byte-key>' }\n */\n fromUntaggedCbor(cborValue: Cbor): ECPublicKey {\n const map = expectMap(cborValue);\n\n // Check that key 2 is not present (would indicate private key)\n const isPrivate = map.get<number, boolean>(2);\n if (isPrivate === true) {\n throw new Error(\"Expected ECPublicKey but found private key (key 2 is true)\");\n }\n\n // Get key data from key 3\n // CborMap.extract() returns native types (Uint8Array for byte strings)\n const keyData = map.extract<number, Uint8Array>(3);\n if (keyData === undefined || keyData.length === 0) {\n throw new Error(\"ECPublicKey CBOR must have key 3 (data)\");\n }\n\n return ECPublicKey.fromDataRef(keyData);\n }\n\n /**\n * Creates an ECPublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): ECPublicKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): ECPublicKey {\n const dummy = new ECPublicKey(new Uint8Array(ECDSA_PUBLIC_KEY_SIZE));\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): ECPublicKey {\n const cborValue = decodeCbor(data);\n return ECPublicKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): ECPublicKey {\n const cborValue = decodeCbor(data);\n const dummy = new ECPublicKey(new Uint8Array(ECDSA_PUBLIC_KEY_SIZE));\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the ECPublicKey.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n const name = TAG_EC_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_EC_KEY.name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an ECPublicKey from a UR.\n */\n static fromUR(ur: UR): ECPublicKey {\n const name = TAG_EC_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_EC_KEY.name is undefined\");\n }\n ur.checkType(name);\n const dummy = new ECPublicKey(new Uint8Array(ECDSA_PUBLIC_KEY_SIZE));\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an ECPublicKey from a UR string.\n */\n static fromURString(urString: string): ECPublicKey {\n const ur = UR.fromURString(urString);\n return ECPublicKey.fromUR(ur);\n }\n}\n","/**\n * Schnorr (x-only) public key for BIP-340 signatures (secp256k1, 32 bytes)\n *\n * A `SchnorrPublicKey` is a 32-byte \"x-only\" public key used with the BIP-340\n * Schnorr signature scheme. Unlike compressed ECDSA public keys (33 bytes)\n * that include a prefix byte indicating the parity of the y-coordinate,\n * Schnorr public keys only contain the x-coordinate of the elliptic curve\n * point.\n *\n * Schnorr signatures offer several advantages over traditional ECDSA\n * signatures:\n * - Linearity: Enables key and signature aggregation\n * - Non-malleability: Prevents third parties from modifying signatures\n * - Smaller size: Signatures are 64 bytes vs 70-72 bytes for ECDSA\n * - Better privacy: Makes different multisig policies indistinguishable\n *\n * Schnorr signatures were introduced to Bitcoin via the Taproot upgrade\n * (BIP-340).\n *\n * Note: SchnorrPublicKey does not have CBOR serialization in the Rust\n * implementation, so we keep it simple here.\n *\n * Ported from bc-components-rust/src/ec_key/schnorr_public_key.rs\n */\n\nimport { SCHNORR_PUBLIC_KEY_SIZE, schnorrVerify } from \"@bcts/crypto\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\nimport type { ECKeyBase } from \"./ec-key-base.js\";\n\nexport class SchnorrPublicKey implements ECKeyBase {\n static readonly KEY_SIZE = SCHNORR_PUBLIC_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== SCHNORR_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(SCHNORR_PUBLIC_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Restore a SchnorrPublicKey from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): SchnorrPublicKey {\n return new SchnorrPublicKey(new Uint8Array(data));\n }\n\n /**\n * Restore a SchnorrPublicKey from a reference to an array of bytes.\n * Validates the length.\n */\n static fromDataRef(data: Uint8Array): SchnorrPublicKey {\n if (data.length !== SCHNORR_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(SCHNORR_PUBLIC_KEY_SIZE, data.length);\n }\n return SchnorrPublicKey.fromData(data);\n }\n\n /**\n * Create a SchnorrPublicKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): SchnorrPublicKey {\n return SchnorrPublicKey.fromData(data);\n }\n\n /**\n * Restore a SchnorrPublicKey from a hex string.\n */\n static fromHex(hex: string): SchnorrPublicKey {\n return SchnorrPublicKey.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw public key bytes (copy).\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Verify a Schnorr signature (BIP-340).\n *\n * @param signature - The 64-byte signature to verify\n * @param message - The message that was signed\n * @returns true if the signature is valid\n */\n schnorrVerify(signature: Uint8Array, message: Uint8Array): boolean {\n try {\n return schnorrVerify(this._data, signature, message);\n } catch {\n return false;\n }\n }\n\n /**\n * Compare with another SchnorrPublicKey.\n */\n equals(other: SchnorrPublicKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `SchnorrPublicKey(${this.toHex().substring(0, 16)}...)`;\n }\n}\n","/**\n * EC private key for ECDSA and Schnorr signatures (secp256k1, 32 bytes)\n *\n * An `ECPrivateKey` is a 32-byte secret value that can be used to:\n * - Generate its corresponding public key\n * - Sign messages using the ECDSA signature scheme\n * - Sign messages using the Schnorr signature scheme (BIP-340)\n *\n * These keys use the secp256k1 curve, which is the same curve used in Bitcoin\n * and other cryptocurrencies.\n *\n * # CBOR Serialization\n *\n * `ECPrivateKey` is serialized to CBOR with tags 40306 (or legacy 306).\n *\n * The format is a map:\n * ```\n * #6.40306({\n * 2: true, // indicates private key\n * 3: h'<32-byte-private-key>' // key data\n * })\n * ```\n *\n * Ported from bc-components-rust/src/ec_key/ec_private_key.rs\n */\n\nimport { SecureRandomNumberGenerator, type RandomNumberGenerator } from \"@bcts/rand\";\nimport {\n ECDSA_PRIVATE_KEY_SIZE,\n ecdsaPublicKeyFromPrivateKey,\n ecdsaDerivePrivateKey,\n ecdsaSign,\n schnorrPublicKeyFromPrivateKey,\n schnorrSign,\n schnorrSignUsing,\n} from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectMap,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { EC_KEY as TAG_EC_KEY, EC_KEY_V1 as TAG_EC_KEY_V1 } from \"@bcts/tags\";\nimport { CryptoError } from \"../error.js\";\nimport { ECPublicKey } from \"./ec-public-key.js\";\nimport { SchnorrPublicKey } from \"./schnorr-public-key.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\nimport type { ECKey } from \"./ec-key-base.js\";\n\nexport class ECPrivateKey\n implements ECKey, CborTaggedEncodable, CborTaggedDecodable<ECPrivateKey>, UREncodable\n{\n static readonly KEY_SIZE = ECDSA_PRIVATE_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n private _publicKey?: ECPublicKey;\n private _schnorrPublicKey?: SchnorrPublicKey;\n\n private constructor(data: Uint8Array) {\n if (data.length !== ECDSA_PRIVATE_KEY_SIZE) {\n throw CryptoError.invalidSize(ECDSA_PRIVATE_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Generate a new random ECPrivateKey.\n */\n static new(): ECPrivateKey {\n return ECPrivateKey.random();\n }\n\n /**\n * Generate a new random ECPrivateKey.\n */\n static random(): ECPrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return ECPrivateKey.newUsing(rng);\n }\n\n /**\n * Generate a new random ECPrivateKey using provided RNG.\n */\n static newUsing(rng: RandomNumberGenerator): ECPrivateKey {\n return new ECPrivateKey(rng.randomData(ECDSA_PRIVATE_KEY_SIZE));\n }\n\n /**\n * Generate a new random ECPrivateKey and corresponding ECPublicKey.\n */\n static keypair(): [ECPrivateKey, ECPublicKey] {\n const privateKey = ECPrivateKey.new();\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Generate a new random ECPrivateKey and corresponding ECPublicKey\n * using the given random number generator.\n */\n static keypairUsing(rng: RandomNumberGenerator): [ECPrivateKey, ECPublicKey] {\n const privateKey = ECPrivateKey.newUsing(rng);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Derive an ECPrivateKey from the given key material.\n *\n * @param keyMaterial - The key material to derive from\n * @returns A new ECPrivateKey derived from the key material\n */\n static deriveFromKeyMaterial(keyMaterial: Uint8Array): ECPrivateKey {\n return new ECPrivateKey(ecdsaDerivePrivateKey(keyMaterial));\n }\n\n /**\n * Restore an ECPrivateKey from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): ECPrivateKey {\n return new ECPrivateKey(new Uint8Array(data));\n }\n\n /**\n * Restore an ECPrivateKey from a reference to an array of bytes.\n * Validates the length.\n */\n static fromDataRef(data: Uint8Array): ECPrivateKey {\n if (data.length !== ECDSA_PRIVATE_KEY_SIZE) {\n throw CryptoError.invalidSize(ECDSA_PRIVATE_KEY_SIZE, data.length);\n }\n return ECPrivateKey.fromData(data);\n }\n\n /**\n * Create an ECPrivateKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): ECPrivateKey {\n return ECPrivateKey.fromData(data);\n }\n\n /**\n * Restore an ECPrivateKey from a hex string.\n */\n static fromHex(hex: string): ECPrivateKey {\n return ECPrivateKey.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw private key bytes (copy).\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Get the ECPublicKey (compressed) corresponding to this ECPrivateKey.\n */\n publicKey(): ECPublicKey {\n if (this._publicKey === undefined) {\n const publicKeyBytes = ecdsaPublicKeyFromPrivateKey(this._data);\n this._publicKey = ECPublicKey.fromData(publicKeyBytes);\n }\n return this._publicKey;\n }\n\n /**\n * Get the SchnorrPublicKey (x-only) corresponding to this ECPrivateKey.\n */\n schnorrPublicKey(): SchnorrPublicKey {\n if (this._schnorrPublicKey === undefined) {\n const publicKeyBytes = schnorrPublicKeyFromPrivateKey(this._data);\n this._schnorrPublicKey = SchnorrPublicKey.fromData(publicKeyBytes);\n }\n return this._schnorrPublicKey;\n }\n\n /**\n * Sign a message using ECDSA.\n *\n * @param message - The message to sign\n * @returns A 64-byte signature\n */\n ecdsaSign(message: Uint8Array): Uint8Array {\n try {\n return ecdsaSign(this._data, message);\n } catch (e) {\n throw CryptoError.cryptoOperation(`ECDSA signing failed: ${String(e)}`);\n }\n }\n\n /**\n * Sign a message using Schnorr signature (BIP-340).\n *\n * @param message - The message to sign\n * @returns A 64-byte signature\n */\n schnorrSign(message: Uint8Array): Uint8Array {\n try {\n return schnorrSign(this._data, message);\n } catch (e) {\n throw CryptoError.cryptoOperation(`Schnorr signing failed: ${String(e)}`);\n }\n }\n\n /**\n * Sign a message using Schnorr signature with custom RNG.\n *\n * @param message - The message to sign\n * @param rng - Random number generator for auxiliary randomness\n * @returns A 64-byte signature\n */\n schnorrSignUsing(message: Uint8Array, rng: RandomNumberGenerator): Uint8Array {\n try {\n return schnorrSignUsing(this._data, message, rng);\n } catch (e) {\n throw CryptoError.cryptoOperation(`Schnorr signing failed: ${String(e)}`);\n }\n }\n\n /**\n * Compare with another ECPrivateKey.\n */\n equals(other: ECPrivateKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `ECPrivateKey(${this.toHex().substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with ECPrivateKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_EC_KEY.value, TAG_EC_KEY_V1.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: { 2: true, 3: h'<32-byte-key>' }\n */\n untaggedCbor(): Cbor {\n const map = new Map<number, unknown>();\n map.set(2, true);\n map.set(3, toByteString(this._data));\n return cbor(map);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an ECPrivateKey by decoding it from untagged CBOR.\n *\n * Format: { 2: true, 3: h'<32-byte-key>' }\n */\n fromUntaggedCbor(cborValue: Cbor): ECPrivateKey {\n const map = expectMap(cborValue);\n\n // Check for key 2 (isPrivate = true)\n const isPrivate = map.get<number, boolean>(2);\n if (isPrivate !== true) {\n throw new Error(\"ECPrivateKey CBOR must have key 2 set to true\");\n }\n\n // Get key data from key 3\n // CborMap.extract() returns native types (Uint8Array for byte strings)\n const keyData = map.extract<number, Uint8Array>(3);\n if (keyData === undefined || keyData.length === 0) {\n throw new Error(\"ECPrivateKey CBOR must have key 3 (data)\");\n }\n\n return ECPrivateKey.fromDataRef(keyData);\n }\n\n /**\n * Creates an ECPrivateKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): ECPrivateKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): ECPrivateKey {\n const dummy = new ECPrivateKey(new Uint8Array(ECDSA_PRIVATE_KEY_SIZE));\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): ECPrivateKey {\n const cborValue = decodeCbor(data);\n return ECPrivateKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): ECPrivateKey {\n const cborValue = decodeCbor(data);\n const dummy = new ECPrivateKey(new Uint8Array(ECDSA_PRIVATE_KEY_SIZE));\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the ECPrivateKey.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n const name = TAG_EC_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_EC_KEY.name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an ECPrivateKey from a UR.\n */\n static fromUR(ur: UR): ECPrivateKey {\n const name = TAG_EC_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_EC_KEY.name is undefined\");\n }\n ur.checkType(name);\n const dummy = new ECPrivateKey(new Uint8Array(ECDSA_PRIVATE_KEY_SIZE));\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an ECPrivateKey from a UR string.\n */\n static fromURString(urString: string): ECPrivateKey {\n const ur = UR.fromURString(urString);\n return ECPrivateKey.fromUR(ur);\n }\n}\n","/**\n * MLDSA Security Level - ML-DSA (Module-Lattice-Based Digital Signature Algorithm)\n *\n * ML-DSA is a post-quantum digital signature algorithm standardized by NIST.\n * It provides three security levels corresponding to different NIST security categories.\n *\n * Security levels:\n * - MLDSA44: NIST Level 2 (equivalent to AES-128)\n * - MLDSA65: NIST Level 3 (equivalent to AES-192)\n * - MLDSA87: NIST Level 5 (equivalent to AES-256)\n *\n * Ported from bc-components-rust/src/mldsa/mldsa_level.rs\n */\n\nimport { ml_dsa44, ml_dsa65, ml_dsa87 } from \"@noble/post-quantum/ml-dsa.js\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\n\n/**\n * ML-DSA security levels.\n *\n * The numeric values correspond to NIST security levels:\n * - 2: NIST Level 2 (MLDSA44)\n * - 3: NIST Level 3 (MLDSA65)\n * - 5: NIST Level 5 (MLDSA87)\n */\nexport enum MLDSALevel {\n /** NIST Level 2 - AES-128 equivalent security */\n MLDSA44 = 2,\n /** NIST Level 3 - AES-192 equivalent security */\n MLDSA65 = 3,\n /** NIST Level 5 - AES-256 equivalent security */\n MLDSA87 = 5,\n}\n\n/**\n * Key sizes for each ML-DSA security level.\n */\nexport const MLDSA_KEY_SIZES = {\n [MLDSALevel.MLDSA44]: {\n privateKey: 2560,\n publicKey: 1312,\n signature: 2420,\n },\n [MLDSALevel.MLDSA65]: {\n privateKey: 4032,\n publicKey: 1952,\n signature: 3309,\n },\n [MLDSALevel.MLDSA87]: {\n privateKey: 4896,\n publicKey: 2592,\n signature: 4627,\n },\n} as const;\n\n/**\n * Get the private key size for a given ML-DSA level.\n */\nexport function mldsaPrivateKeySize(level: MLDSALevel): number {\n return MLDSA_KEY_SIZES[level].privateKey;\n}\n\n/**\n * Get the public key size for a given ML-DSA level.\n */\nexport function mldsaPublicKeySize(level: MLDSALevel): number {\n return MLDSA_KEY_SIZES[level].publicKey;\n}\n\n/**\n * Get the signature size for a given ML-DSA level.\n */\nexport function mldsaSignatureSize(level: MLDSALevel): number {\n return MLDSA_KEY_SIZES[level].signature;\n}\n\n/**\n * Convert an ML-DSA level to its string representation.\n */\nexport function mldsaLevelToString(level: MLDSALevel): string {\n switch (level) {\n case MLDSALevel.MLDSA44:\n return \"MLDSA44\";\n case MLDSALevel.MLDSA65:\n return \"MLDSA65\";\n case MLDSALevel.MLDSA87:\n return \"MLDSA87\";\n }\n}\n\n/**\n * Parse an ML-DSA level from its numeric value.\n */\nexport function mldsaLevelFromValue(value: number): MLDSALevel {\n switch (value) {\n case 2:\n return MLDSALevel.MLDSA44;\n case 3:\n return MLDSALevel.MLDSA65;\n case 5:\n return MLDSALevel.MLDSA87;\n default:\n throw new Error(`Invalid MLDSA level value: ${value}`);\n }\n}\n\n/**\n * Internal type for ML-DSA keypair generation result.\n */\nexport interface MLDSAKeypairData {\n publicKey: Uint8Array;\n secretKey: Uint8Array;\n}\n\n/**\n * Generate an ML-DSA keypair for the given security level.\n *\n * @param level - The ML-DSA security level\n * @returns Object containing publicKey and secretKey bytes\n */\nexport function mldsaGenerateKeypair(level: MLDSALevel): MLDSAKeypairData {\n const rng = new SecureRandomNumberGenerator();\n return mldsaGenerateKeypairUsing(level, rng);\n}\n\n/**\n * Generate an ML-DSA keypair using a provided RNG.\n *\n * @param level - The ML-DSA security level\n * @param rng - Random number generator\n * @returns Object containing publicKey and secretKey bytes\n */\nexport function mldsaGenerateKeypairUsing(\n level: MLDSALevel,\n rng: RandomNumberGenerator,\n): MLDSAKeypairData {\n // Generate random seed for keypair generation\n const seed = rng.randomData(32);\n\n switch (level) {\n case MLDSALevel.MLDSA44: {\n const keypair = ml_dsa44.keygen(seed);\n return { publicKey: keypair.publicKey, secretKey: keypair.secretKey };\n }\n case MLDSALevel.MLDSA65: {\n const keypair = ml_dsa65.keygen(seed);\n return { publicKey: keypair.publicKey, secretKey: keypair.secretKey };\n }\n case MLDSALevel.MLDSA87: {\n const keypair = ml_dsa87.keygen(seed);\n return { publicKey: keypair.publicKey, secretKey: keypair.secretKey };\n }\n }\n}\n\n/**\n * Sign a message using ML-DSA.\n *\n * @param level - The ML-DSA security level\n * @param secretKey - The secret key bytes\n * @param message - The message to sign\n * @returns The signature bytes\n */\nexport function mldsaSign(\n level: MLDSALevel,\n secretKey: Uint8Array,\n message: Uint8Array,\n): Uint8Array {\n switch (level) {\n case MLDSALevel.MLDSA44:\n return ml_dsa44.sign(message, secretKey);\n case MLDSALevel.MLDSA65:\n return ml_dsa65.sign(message, secretKey);\n case MLDSALevel.MLDSA87:\n return ml_dsa87.sign(message, secretKey);\n }\n}\n\n/**\n * Verify a signature using ML-DSA.\n *\n * @param level - The ML-DSA security level\n * @param publicKey - The public key bytes\n * @param message - The message that was signed\n * @param signature - The signature to verify\n * @returns True if the signature is valid\n */\nexport function mldsaVerify(\n level: MLDSALevel,\n publicKey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array,\n): boolean {\n try {\n switch (level) {\n case MLDSALevel.MLDSA44:\n return ml_dsa44.verify(signature, message, publicKey);\n case MLDSALevel.MLDSA65:\n return ml_dsa65.verify(signature, message, publicKey);\n case MLDSALevel.MLDSA87:\n return ml_dsa87.verify(signature, message, publicKey);\n }\n } catch {\n return false;\n }\n}\n","/**\n * MLDSAPublicKey - ML-DSA Public Key for post-quantum signature verification\n *\n * MLDSAPublicKey wraps an ML-DSA public key for verifying signatures.\n * It supports all three security levels (MLDSA44, MLDSA65, MLDSA87).\n *\n * # CBOR Serialization\n *\n * MLDSAPublicKey is serialized with tag 40104:\n * ```\n * #6.40104([level, h'<public-key-bytes>'])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `mldsa-public-key`\n *\n * Ported from bc-components-rust/src/mldsa/mldsa_public_key.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n expectInteger,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { MLDSA_PUBLIC_KEY as TAG_MLDSA_PUBLIC_KEY } from \"@bcts/tags\";\n\nimport {\n MLDSALevel,\n mldsaLevelFromValue,\n mldsaLevelToString,\n mldsaPublicKeySize,\n mldsaVerify,\n} from \"./mldsa-level.js\";\nimport type { MLDSASignature } from \"./mldsa-signature.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * MLDSAPublicKey - Post-quantum signature verification key using ML-DSA.\n */\nexport class MLDSAPublicKey\n implements CborTaggedEncodable, CborTaggedDecodable<MLDSAPublicKey>, UREncodable\n{\n private readonly _level: MLDSALevel;\n private readonly _data: Uint8Array;\n\n private constructor(level: MLDSALevel, data: Uint8Array) {\n const expectedSize = mldsaPublicKeySize(level);\n if (data.length !== expectedSize) {\n throw new Error(\n `MLDSAPublicKey (${mldsaLevelToString(level)}) must be ${expectedSize} bytes, got ${data.length}`,\n );\n }\n this._level = level;\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an MLDSAPublicKey from raw bytes.\n *\n * @param level - The ML-DSA security level\n * @param data - The public key bytes\n */\n static fromBytes(level: MLDSALevel, data: Uint8Array): MLDSAPublicKey {\n return new MLDSAPublicKey(level, data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the security level of this key.\n */\n level(): MLDSALevel {\n return this._level;\n }\n\n /**\n * Returns the raw key bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw key bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the size of the key in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n /**\n * Verify a signature against a message.\n *\n * @param signature - The ML-DSA signature to verify\n * @param message - The message that was signed\n * @returns True if the signature is valid\n */\n verify(signature: MLDSASignature, message: Uint8Array): boolean {\n if (signature.level() !== this._level) {\n return false;\n }\n return mldsaVerify(this._level, this._data, message, signature.asBytes());\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another MLDSAPublicKey.\n */\n equals(other: MLDSAPublicKey): boolean {\n if (this._level !== other._level) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `MLDSAPublicKey(${mldsaLevelToString(this._level)}, ${hex.substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with MLDSAPublicKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_MLDSA_PUBLIC_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [level, key_bytes]\n */\n untaggedCbor(): Cbor {\n return cbor([this._level, this._data]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an MLDSAPublicKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): MLDSAPublicKey {\n const elements = expectArray(cborValue);\n if (elements.length !== 2) {\n throw new Error(`MLDSAPublicKey CBOR must have 2 elements, got ${elements.length}`);\n }\n const levelValue = Number(expectInteger(elements[0]));\n const level = mldsaLevelFromValue(levelValue);\n const data = expectBytes(elements[1]);\n return MLDSAPublicKey.fromBytes(level, data);\n }\n\n /**\n * Creates an MLDSAPublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): MLDSAPublicKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): MLDSAPublicKey {\n // Create a minimal dummy instance for decoding\n const dummyData = new Uint8Array(mldsaPublicKeySize(MLDSALevel.MLDSA44));\n const dummy = new MLDSAPublicKey(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): MLDSAPublicKey {\n const cborValue = decodeCbor(data);\n return MLDSAPublicKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): MLDSAPublicKey {\n const cborValue = decodeCbor(data);\n const dummyData = new Uint8Array(mldsaPublicKeySize(MLDSALevel.MLDSA44));\n const dummy = new MLDSAPublicKey(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_MLDSA_PUBLIC_KEY.name;\n if (name === undefined) {\n throw new Error(\"MLDSA_PUBLIC_KEY tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an MLDSAPublicKey from a UR.\n */\n static fromUR(ur: UR): MLDSAPublicKey {\n if (ur.urTypeStr() !== TAG_MLDSA_PUBLIC_KEY.name) {\n throw new Error(`Expected UR type ${TAG_MLDSA_PUBLIC_KEY.name}, got ${ur.urTypeStr()}`);\n }\n const dummyData = new Uint8Array(mldsaPublicKeySize(MLDSALevel.MLDSA44));\n const dummy = new MLDSAPublicKey(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an MLDSAPublicKey from a UR string.\n */\n static fromURString(urString: string): MLDSAPublicKey {\n const ur = UR.fromURString(urString);\n return MLDSAPublicKey.fromUR(ur);\n }\n}\n","/**\n * MLDSASignature - ML-DSA Digital Signature\n *\n * MLDSASignature wraps an ML-DSA signature for serialization and verification.\n * It supports all three security levels (MLDSA44, MLDSA65, MLDSA87).\n *\n * # CBOR Serialization\n *\n * MLDSASignature is serialized with tag 40105:\n * ```\n * #6.40105([level, h'<signature-bytes>'])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `mldsa-signature`\n *\n * Ported from bc-components-rust/src/mldsa/mldsa_signature.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n expectInteger,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { MLDSA_SIGNATURE as TAG_MLDSA_SIGNATURE } from \"@bcts/tags\";\n\nimport {\n MLDSALevel,\n mldsaLevelFromValue,\n mldsaLevelToString,\n mldsaSignatureSize,\n} from \"./mldsa-level.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * MLDSASignature - Post-quantum digital signature using ML-DSA.\n */\nexport class MLDSASignature\n implements CborTaggedEncodable, CborTaggedDecodable<MLDSASignature>, UREncodable\n{\n private readonly _level: MLDSALevel;\n private readonly _data: Uint8Array;\n\n private constructor(level: MLDSALevel, data: Uint8Array) {\n const expectedSize = mldsaSignatureSize(level);\n if (data.length !== expectedSize) {\n throw new Error(\n `MLDSASignature (${mldsaLevelToString(level)}) must be ${expectedSize} bytes, got ${data.length}`,\n );\n }\n this._level = level;\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an MLDSASignature from raw bytes.\n *\n * @param level - The ML-DSA security level\n * @param data - The signature bytes\n */\n static fromBytes(level: MLDSALevel, data: Uint8Array): MLDSASignature {\n return new MLDSASignature(level, data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the security level of this signature.\n */\n level(): MLDSALevel {\n return this._level;\n }\n\n /**\n * Returns the raw signature bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw signature bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the size of the signature in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another MLDSASignature.\n */\n equals(other: MLDSASignature): boolean {\n if (this._level !== other._level) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `MLDSASignature(${mldsaLevelToString(this._level)}, ${hex.substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with MLDSASignature.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_MLDSA_SIGNATURE.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [level, signature_bytes]\n */\n untaggedCbor(): Cbor {\n return cbor([this._level, this._data]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an MLDSASignature by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): MLDSASignature {\n const elements = expectArray(cborValue);\n if (elements.length !== 2) {\n throw new Error(`MLDSASignature CBOR must have 2 elements, got ${elements.length}`);\n }\n const levelValue = Number(expectInteger(elements[0]));\n const level = mldsaLevelFromValue(levelValue);\n const data = expectBytes(elements[1]);\n return MLDSASignature.fromBytes(level, data);\n }\n\n /**\n * Creates an MLDSASignature by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): MLDSASignature {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): MLDSASignature {\n // Create a minimal dummy instance for decoding\n const dummyData = new Uint8Array(mldsaSignatureSize(MLDSALevel.MLDSA44));\n const dummy = new MLDSASignature(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): MLDSASignature {\n const cborValue = decodeCbor(data);\n return MLDSASignature.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): MLDSASignature {\n const cborValue = decodeCbor(data);\n const dummyData = new Uint8Array(mldsaSignatureSize(MLDSALevel.MLDSA44));\n const dummy = new MLDSASignature(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_MLDSA_SIGNATURE.name;\n if (name === undefined) {\n throw new Error(\"MLDSA_SIGNATURE tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an MLDSASignature from a UR.\n */\n static fromUR(ur: UR): MLDSASignature {\n if (ur.urTypeStr() !== TAG_MLDSA_SIGNATURE.name) {\n throw new Error(`Expected UR type ${TAG_MLDSA_SIGNATURE.name}, got ${ur.urTypeStr()}`);\n }\n const dummyData = new Uint8Array(mldsaSignatureSize(MLDSALevel.MLDSA44));\n const dummy = new MLDSASignature(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an MLDSASignature from a UR string.\n */\n static fromURString(urString: string): MLDSASignature {\n const ur = UR.fromURString(urString);\n return MLDSASignature.fromUR(ur);\n }\n}\n","/**\n * MLDSAPrivateKey - ML-DSA Private Key for post-quantum digital signatures\n *\n * MLDSAPrivateKey wraps an ML-DSA secret key for signing messages.\n * It supports all three security levels (MLDSA44, MLDSA65, MLDSA87).\n *\n * # CBOR Serialization\n *\n * MLDSAPrivateKey is serialized with tag 40103:\n * ```\n * #6.40103([level, h'<private-key-bytes>'])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `mldsa-private-key`\n *\n * Ported from bc-components-rust/src/mldsa/mldsa_private_key.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n expectInteger,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { MLDSA_PRIVATE_KEY as TAG_MLDSA_PRIVATE_KEY } from \"@bcts/tags\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\n\nimport {\n MLDSALevel,\n mldsaLevelFromValue,\n mldsaLevelToString,\n mldsaPrivateKeySize,\n mldsaGenerateKeypairUsing,\n mldsaSign,\n} from \"./mldsa-level.js\";\nimport { MLDSAPublicKey } from \"./mldsa-public-key.js\";\nimport { MLDSASignature } from \"./mldsa-signature.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * MLDSAPrivateKey - Post-quantum signing private key using ML-DSA.\n */\nexport class MLDSAPrivateKey\n implements CborTaggedEncodable, CborTaggedDecodable<MLDSAPrivateKey>, UREncodable\n{\n private readonly _level: MLDSALevel;\n private readonly _data: Uint8Array;\n\n private constructor(level: MLDSALevel, data: Uint8Array) {\n const expectedSize = mldsaPrivateKeySize(level);\n if (data.length !== expectedSize) {\n throw new Error(\n `MLDSAPrivateKey (${mldsaLevelToString(level)}) must be ${expectedSize} bytes, got ${data.length}`,\n );\n }\n this._level = level;\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Generate a new random MLDSAPrivateKey with the specified security level.\n *\n * @param level - The ML-DSA security level (default: MLDSA65)\n */\n static new(level: MLDSALevel = MLDSALevel.MLDSA65): MLDSAPrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return MLDSAPrivateKey.newUsing(level, rng);\n }\n\n /**\n * Generate a new random MLDSAPrivateKey using the provided RNG.\n *\n * @param level - The ML-DSA security level\n * @param rng - Random number generator\n */\n static newUsing(level: MLDSALevel, rng: RandomNumberGenerator): MLDSAPrivateKey {\n const keypair = mldsaGenerateKeypairUsing(level, rng);\n return new MLDSAPrivateKey(level, keypair.secretKey);\n }\n\n /**\n * Create an MLDSAPrivateKey from raw bytes.\n *\n * @param level - The ML-DSA security level\n * @param data - The private key bytes\n */\n static fromBytes(level: MLDSALevel, data: Uint8Array): MLDSAPrivateKey {\n return new MLDSAPrivateKey(level, data);\n }\n\n /**\n * Generate a keypair and return both private and public keys.\n *\n * @param level - The ML-DSA security level (default: MLDSA65)\n * @returns Tuple of [privateKey, publicKey]\n */\n static keypair(level: MLDSALevel = MLDSALevel.MLDSA65): [MLDSAPrivateKey, MLDSAPublicKey] {\n const rng = new SecureRandomNumberGenerator();\n return MLDSAPrivateKey.keypairUsing(level, rng);\n }\n\n /**\n * Generate a keypair using the provided RNG.\n *\n * @param level - The ML-DSA security level\n * @param rng - Random number generator\n * @returns Tuple of [privateKey, publicKey]\n */\n static keypairUsing(\n level: MLDSALevel,\n rng: RandomNumberGenerator,\n ): [MLDSAPrivateKey, MLDSAPublicKey] {\n const keypairData = mldsaGenerateKeypairUsing(level, rng);\n const privateKey = new MLDSAPrivateKey(level, keypairData.secretKey);\n const publicKey = MLDSAPublicKey.fromBytes(level, keypairData.publicKey);\n return [privateKey, publicKey];\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the security level of this key.\n */\n level(): MLDSALevel {\n return this._level;\n }\n\n /**\n * Returns the raw key bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw key bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the size of the key in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n /**\n * Sign a message with this private key.\n *\n * @param message - The message to sign\n * @returns The ML-DSA signature\n */\n sign(message: Uint8Array): MLDSASignature {\n const sigBytes = mldsaSign(this._level, this._data, message);\n return MLDSASignature.fromBytes(this._level, sigBytes);\n }\n\n /**\n * Derive the public key from this private key.\n *\n * Note: ML-DSA doesn't have a direct derivation method, so we need to\n * regenerate the keypair from seed. For now, we extract from the secret key\n * structure (the public key is embedded in the secret key for ML-DSA).\n */\n publicKey(): MLDSAPublicKey {\n // In ML-DSA, the public key can be extracted from the secret key\n // The noble library stores (secretKey, publicKey) concatenated\n // For MLDSA44: secretKey = 2560 bytes, publicKey = 1312 bytes\n // For MLDSA65: secretKey = 4032 bytes, publicKey = 1952 bytes\n // For MLDSA87: secretKey = 4896 bytes, publicKey = 2592 bytes\n\n // Actually, noble stores them separately in keygen(), and the secret key\n // doesn't contain the public key. We need to regenerate or cache.\n // For simplicity, we'll generate a new keypair with the same seed.\n // But we don't have the seed... This is a limitation.\n\n // The solution is to either:\n // 1. Store the public key alongside the private key\n // 2. Re-generate from seed (but we don't have it)\n // 3. Use a deterministic derivation\n\n // For now, we'll throw an error and require users to use keypair() instead.\n // This matches the Rust implementation where public_key() uses the internal\n // key structure which may have the public key embedded.\n\n // Actually, looking at the noble implementation, we can't easily extract\n // the public key. The keypair generation is what produces both.\n // So we need to either:\n // a) Store both keys together\n // b) Require users to keep track of both\n\n // For MVP, we'll throw an error suggesting to use keypair()\n throw new Error(\n \"MLDSAPrivateKey.publicKey() is not supported. Use MLDSAPrivateKey.keypair() to generate both keys together.\",\n );\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another MLDSAPrivateKey.\n */\n equals(other: MLDSAPrivateKey): boolean {\n if (this._level !== other._level) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation (truncated for security).\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `MLDSAPrivateKey(${mldsaLevelToString(this._level)}, ${hex.substring(0, 8)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with MLDSAPrivateKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_MLDSA_PRIVATE_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [level, key_bytes]\n */\n untaggedCbor(): Cbor {\n return cbor([this._level, this._data]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an MLDSAPrivateKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): MLDSAPrivateKey {\n const elements = expectArray(cborValue);\n if (elements.length !== 2) {\n throw new Error(`MLDSAPrivateKey CBOR must have 2 elements, got ${elements.length}`);\n }\n const levelValue = Number(expectInteger(elements[0]));\n const level = mldsaLevelFromValue(levelValue);\n const data = expectBytes(elements[1]);\n return MLDSAPrivateKey.fromBytes(level, data);\n }\n\n /**\n * Creates an MLDSAPrivateKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): MLDSAPrivateKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): MLDSAPrivateKey {\n // Create a minimal dummy instance for decoding\n const dummyData = new Uint8Array(mldsaPrivateKeySize(MLDSALevel.MLDSA44));\n const dummy = new MLDSAPrivateKey(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): MLDSAPrivateKey {\n const cborValue = decodeCbor(data);\n return MLDSAPrivateKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): MLDSAPrivateKey {\n const cborValue = decodeCbor(data);\n const dummyData = new Uint8Array(mldsaPrivateKeySize(MLDSALevel.MLDSA44));\n const dummy = new MLDSAPrivateKey(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_MLDSA_PRIVATE_KEY.name;\n if (name === undefined) {\n throw new Error(\"MLDSA_PRIVATE_KEY tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an MLDSAPrivateKey from a UR.\n */\n static fromUR(ur: UR): MLDSAPrivateKey {\n if (ur.urTypeStr() !== TAG_MLDSA_PRIVATE_KEY.name) {\n throw new Error(`Expected UR type ${TAG_MLDSA_PRIVATE_KEY.name}, got ${ur.urTypeStr()}`);\n }\n const dummyData = new Uint8Array(mldsaPrivateKeySize(MLDSALevel.MLDSA44));\n const dummy = new MLDSAPrivateKey(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an MLDSAPrivateKey from a UR string.\n */\n static fromURString(urString: string): MLDSAPrivateKey {\n const ur = UR.fromURString(urString);\n return MLDSAPrivateKey.fromUR(ur);\n }\n}\n","/**\n * A digital signature created with various signature algorithms.\n *\n * `Signature` represents different types of digital signatures.\n * Supports Schnorr, ECDSA, Ed25519, and Sr25519 signatures.\n *\n * Signatures can be serialized to and from CBOR with tag 40020.\n *\n * # CBOR Serialization\n *\n * The CBOR encoding (matching Rust bc-components):\n * - Schnorr: `#6.40020(h'<64-byte-signature>')` (bare byte string)\n * - ECDSA: `#6.40020([1, h'<64-byte-signature>'])`\n * - Ed25519: `#6.40020([2, h'<64-byte-signature>'])`\n * - Sr25519: `#6.40020([3, h'<64-byte-signature>'])`\n *\n * Ported from bc-components-rust/src/signing/signature.rs\n */\n\nimport { ED25519_SIGNATURE_SIZE, ECDSA_SIGNATURE_SIZE, SCHNORR_SIGNATURE_SIZE } from \"@bcts/crypto\";\nimport { SR25519_SIGNATURE_SIZE } from \"../sr25519/sr25519-private-key.js\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectArray,\n expectBytes,\n expectUnsigned,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n isBytes,\n isArray,\n isTagged,\n} from \"@bcts/dcbor\";\nimport { SIGNATURE as TAG_SIGNATURE, MLDSA_SIGNATURE as TAG_MLDSA_SIGNATURE } from \"@bcts/tags\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes } from \"../utils.js\";\nimport { SignatureScheme, isMldsaScheme } from \"./signature-scheme.js\";\nimport { MLDSASignature } from \"../mldsa/mldsa-signature.js\";\nimport { MLDSALevel } from \"../mldsa/mldsa-level.js\";\nimport { UR } from \"@bcts/uniform-resources\";\n\n/**\n * A digital signature created with various signature algorithms.\n *\n * Currently supports:\n * - Schnorr signatures (64 bytes) - bare byte string in CBOR\n * - ECDSA signatures (64 bytes) - discriminator 1\n * - Ed25519 signatures (64 bytes) - discriminator 2\n * - Sr25519 signatures (64 bytes) - discriminator 3\n * - MLDSA signatures (post-quantum) - tagged CBOR delegating to MLDSASignature\n */\nexport class Signature implements CborTaggedEncodable, CborTaggedDecodable<Signature> {\n private readonly _type: SignatureScheme;\n private readonly _data: Uint8Array;\n private readonly _mldsaSignature: MLDSASignature | undefined;\n\n private constructor(type: SignatureScheme, data: Uint8Array, mldsaSignature?: MLDSASignature) {\n this._type = type;\n this._data = new Uint8Array(data);\n this._mldsaSignature = mldsaSignature;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Creates a Schnorr signature from a 64-byte array.\n *\n * @param data - The 64-byte signature data\n * @returns A new Schnorr signature\n */\n static schnorrFromData(data: Uint8Array): Signature {\n if (data.length !== SCHNORR_SIGNATURE_SIZE) {\n throw CryptoError.invalidSize(SCHNORR_SIGNATURE_SIZE, data.length);\n }\n return new Signature(SignatureScheme.Schnorr, data);\n }\n\n /**\n * Creates a Schnorr signature from a hex string.\n *\n * @param hex - The hex-encoded signature data\n * @returns A new Schnorr signature\n */\n static schnorrFromHex(hex: string): Signature {\n return Signature.schnorrFromData(hexToBytes(hex));\n }\n\n /**\n * Creates an ECDSA signature from a 64-byte array.\n *\n * @param data - The 64-byte signature data\n * @returns A new ECDSA signature\n */\n static ecdsaFromData(data: Uint8Array): Signature {\n if (data.length !== ECDSA_SIGNATURE_SIZE) {\n throw CryptoError.invalidSize(ECDSA_SIGNATURE_SIZE, data.length);\n }\n return new Signature(SignatureScheme.Ecdsa, data);\n }\n\n /**\n * Creates an ECDSA signature from a hex string.\n *\n * @param hex - The hex-encoded signature data\n * @returns A new ECDSA signature\n */\n static ecdsaFromHex(hex: string): Signature {\n return Signature.ecdsaFromData(hexToBytes(hex));\n }\n\n /**\n * Creates an Ed25519 signature from a 64-byte array.\n *\n * @param data - The 64-byte signature data\n * @returns A new Ed25519 signature\n */\n static ed25519FromData(data: Uint8Array): Signature {\n if (data.length !== ED25519_SIGNATURE_SIZE) {\n throw CryptoError.invalidSize(ED25519_SIGNATURE_SIZE, data.length);\n }\n return new Signature(SignatureScheme.Ed25519, data);\n }\n\n /**\n * Creates an Ed25519 signature from a hex string.\n *\n * @param hex - The hex-encoded signature data\n * @returns A new Ed25519 signature\n */\n static ed25519FromHex(hex: string): Signature {\n return Signature.ed25519FromData(hexToBytes(hex));\n }\n\n /**\n * Creates an Sr25519 signature from a 64-byte array.\n *\n * @param data - The 64-byte signature data\n * @returns A new Sr25519 signature\n */\n static sr25519FromData(data: Uint8Array): Signature {\n if (data.length !== SR25519_SIGNATURE_SIZE) {\n throw CryptoError.invalidSize(SR25519_SIGNATURE_SIZE, data.length);\n }\n return new Signature(SignatureScheme.Sr25519, data);\n }\n\n /**\n * Creates an Sr25519 signature from a hex string.\n *\n * @param hex - The hex-encoded signature data\n * @returns A new Sr25519 signature\n */\n static sr25519FromHex(hex: string): Signature {\n return Signature.sr25519FromData(hexToBytes(hex));\n }\n\n /**\n * Creates a Signature from an MLDSASignature.\n *\n * @param sig - The MLDSASignature\n * @returns A new Signature wrapping the MLDSA signature\n */\n static mldsaFromSignature(sig: MLDSASignature): Signature {\n // Determine the SignatureScheme based on the MLDSA level\n let scheme: SignatureScheme;\n switch (sig.level()) {\n case MLDSALevel.MLDSA44:\n scheme = SignatureScheme.MLDSA44;\n break;\n case MLDSALevel.MLDSA65:\n scheme = SignatureScheme.MLDSA65;\n break;\n case MLDSALevel.MLDSA87:\n scheme = SignatureScheme.MLDSA87;\n break;\n default:\n throw new Error(`Unknown MLDSA level: ${sig.level()}`);\n }\n return new Signature(scheme, sig.data(), sig);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the signature scheme used to create this signature.\n */\n scheme(): SignatureScheme {\n return this._type;\n }\n\n /**\n * Returns a human-readable string identifying the signature type.\n * @returns A string like \"Ed25519\", \"Schnorr\", \"ECDSA\", \"Sr25519\", \"MLDSA-44\", etc.\n */\n signatureType(): string {\n switch (this._type) {\n case SignatureScheme.Ed25519:\n return \"Ed25519\";\n case SignatureScheme.Schnorr:\n return \"Schnorr\";\n case SignatureScheme.Ecdsa:\n return \"Ecdsa\";\n case SignatureScheme.Sr25519:\n return \"Sr25519\";\n case SignatureScheme.MLDSA44:\n return \"MLDSA-44\";\n case SignatureScheme.MLDSA65:\n return \"MLDSA-65\";\n case SignatureScheme.MLDSA87:\n return \"MLDSA-87\";\n case SignatureScheme.SshEd25519:\n return \"SshEd25519\";\n case SignatureScheme.SshDsa:\n return \"SshDsa\";\n case SignatureScheme.SshEcdsaP256:\n return \"SshEcdsaP256\";\n case SignatureScheme.SshEcdsaP384:\n return \"SshEcdsaP384\";\n default:\n return this._type;\n }\n }\n\n /**\n * Returns the raw signature data.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns the Schnorr signature data if this is a Schnorr signature.\n *\n * @returns The 64-byte signature data if this is a Schnorr signature, null otherwise\n */\n toSchnorr(): Uint8Array | null {\n if (this._type === SignatureScheme.Schnorr) {\n return this._data;\n }\n return null;\n }\n\n /**\n * Checks if this is a Schnorr signature.\n */\n isSchnorr(): boolean {\n return this._type === SignatureScheme.Schnorr;\n }\n\n /**\n * Returns the ECDSA signature data if this is an ECDSA signature.\n *\n * @returns The 64-byte signature data if this is an ECDSA signature, null otherwise\n */\n toEcdsa(): Uint8Array | null {\n if (this._type === SignatureScheme.Ecdsa) {\n return this._data;\n }\n return null;\n }\n\n /**\n * Checks if this is an ECDSA signature.\n */\n isEcdsa(): boolean {\n return this._type === SignatureScheme.Ecdsa;\n }\n\n /**\n * Returns the Ed25519 signature data if this is an Ed25519 signature.\n *\n * @returns The 64-byte signature data if this is an Ed25519 signature, null otherwise\n */\n toEd25519(): Uint8Array | null {\n if (this._type === SignatureScheme.Ed25519) {\n return this._data;\n }\n return null;\n }\n\n /**\n * Checks if this is an Ed25519 signature.\n */\n isEd25519(): boolean {\n return this._type === SignatureScheme.Ed25519;\n }\n\n /**\n * Returns the Sr25519 signature data if this is an Sr25519 signature.\n *\n * @returns The 64-byte signature data if this is an Sr25519 signature, null otherwise\n */\n toSr25519(): Uint8Array | null {\n if (this._type === SignatureScheme.Sr25519) {\n return this._data;\n }\n return null;\n }\n\n /**\n * Checks if this is an Sr25519 signature.\n */\n isSr25519(): boolean {\n return this._type === SignatureScheme.Sr25519;\n }\n\n /**\n * Returns the MLDSASignature if this is an MLDSA signature.\n *\n * @returns The MLDSASignature if this is an MLDSA signature, null otherwise\n */\n toMldsa(): MLDSASignature | null {\n if (isMldsaScheme(this._type) && this._mldsaSignature !== undefined) {\n return this._mldsaSignature;\n }\n return null;\n }\n\n /**\n * Checks if this is an MLDSA signature.\n */\n isMldsa(): boolean {\n return isMldsaScheme(this._type);\n }\n\n /**\n * Get hex string representation of the signature data.\n */\n toHex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Compare with another Signature.\n */\n equals(other: Signature): boolean {\n if (this._type !== other._type) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `Signature(${this._type}, ${this.toHex().substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with Signature.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SIGNATURE.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format (matching Rust bc-components):\n * - Schnorr: h'<64-byte-signature>' (bare byte string)\n * - ECDSA: [1, h'<64-byte-signature>']\n * - Ed25519: [2, h'<64-byte-signature>']\n * - Sr25519: [3, h'<64-byte-signature>']\n */\n untaggedCbor(): Cbor {\n switch (this._type) {\n case SignatureScheme.Schnorr:\n // Rust: CBOR::to_byte_string(data) - bare byte string\n return toByteString(this._data);\n case SignatureScheme.Ecdsa:\n return cbor([1, toByteString(this._data)]);\n case SignatureScheme.Ed25519:\n return cbor([2, toByteString(this._data)]);\n case SignatureScheme.Sr25519:\n return cbor([3, toByteString(this._data)]);\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87: {\n if (this._mldsaSignature === undefined) {\n throw new Error(\"MLDSA signature is missing\");\n }\n // Rust: delegates to MLDSASignature (which produces tagged CBOR)\n return this._mldsaSignature.taggedCbor();\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n throw new Error(`SSH signature scheme ${this._type} is not supported for CBOR encoding`);\n }\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a Signature by decoding it from untagged CBOR.\n *\n * Format (matching Rust bc-components):\n * - h'<64-byte-signature>' (bare byte string) for Schnorr\n * - [1, h'<64-byte-signature>'] for ECDSA\n * - [2, h'<64-byte-signature>'] for Ed25519\n * - [3, h'<64-byte-signature>'] for Sr25519\n */\n fromUntaggedCbor(cborValue: Cbor): Signature {\n // Rust format: Schnorr is a bare byte string\n if (isBytes(cborValue)) {\n const signatureData = expectBytes(cborValue);\n return Signature.schnorrFromData(signatureData);\n }\n\n // Array format for ECDSA, Ed25519, Sr25519\n if (isArray(cborValue)) {\n const elements = expectArray(cborValue);\n\n if (elements.length !== 2) {\n throw new Error(\"Signature array must have 2 elements\");\n }\n\n const discriminator = expectUnsigned(elements[0]);\n const signatureData = expectBytes(elements[1]);\n\n switch (Number(discriminator)) {\n case 1: // ECDSA\n return Signature.ecdsaFromData(signatureData);\n case 2: // Ed25519\n return Signature.ed25519FromData(signatureData);\n case 3: // Sr25519\n return Signature.sr25519FromData(signatureData);\n default:\n throw new Error(`Unknown signature discriminator: ${discriminator}`);\n }\n }\n\n // Tagged format for MLDSA\n if (isTagged(cborValue)) {\n const tagged = cborValue.asTagged();\n if (tagged?.[0].value === TAG_MLDSA_SIGNATURE.value) {\n const mldsaSig = MLDSASignature.fromTaggedCbor(cborValue);\n return Signature.mldsaFromSignature(mldsaSig);\n }\n }\n\n throw new Error(\n \"Signature must be a byte string (Schnorr), array (ECDSA/Ed25519/Sr25519), or tagged MLDSA\",\n );\n }\n\n /**\n * Creates a Signature by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): Signature {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): Signature {\n // Create a dummy instance for accessing instance methods\n const dummy = new Signature(SignatureScheme.Ed25519, new Uint8Array(ED25519_SIGNATURE_SIZE));\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): Signature {\n const cborValue = decodeCbor(data);\n return Signature.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): Signature {\n const cborValue = decodeCbor(data);\n const dummy = new Signature(SignatureScheme.Ed25519, new Uint8Array(ED25519_SIGNATURE_SIZE));\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR (Uniform Resource) Serialization\n // ============================================================================\n\n /**\n * Get the UR type for signatures.\n */\n static readonly UR_TYPE = \"signature\";\n\n /**\n * Returns the UR representation of the signature.\n */\n ur(): UR {\n return UR.new(Signature.UR_TYPE, this.taggedCbor());\n }\n\n /**\n * Returns the UR string representation of the signature.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a Signature from a UR.\n */\n static fromUR(ur: UR): Signature {\n ur.checkType(Signature.UR_TYPE);\n return Signature.fromTaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a Signature from a UR string.\n */\n static fromURString(urString: string): Signature {\n const ur = UR.fromURString(urString);\n return Signature.fromUR(ur);\n }\n\n /**\n * Alias for fromURString for Rust API compatibility.\n */\n static fromUrString(urString: string): Signature {\n return Signature.fromURString(urString);\n }\n}\n","/**\n * A public key used for verifying digital signatures.\n *\n * `SigningPublicKey` is a type representing different types of signing public\n * keys. Supports Schnorr, ECDSA, Ed25519, and SR25519.\n *\n * This type implements the `Verifier` interface, allowing it to verify signatures.\n *\n * # CBOR Serialization\n *\n * `SigningPublicKey` is serialized to CBOR with tag 40022.\n *\n * The CBOR encoding (matching Rust bc-components):\n * - Schnorr: `#6.40022(h'<32-byte-x-only-public-key>')` (bare byte string)\n * - ECDSA: `#6.40022([1, h'<33-byte-compressed-public-key>'])`\n * - Ed25519: `#6.40022([2, h'<32-byte-public-key>'])`\n * - Sr25519: `#6.40022([3, h'<32-byte-public-key>'])`\n *\n * Ported from bc-components-rust/src/signing/signing_public_key.rs\n */\n\nimport { ED25519_PUBLIC_KEY_SIZE } from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectArray,\n expectBytes,\n expectUnsigned,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n isBytes,\n isArray,\n isTagged,\n} from \"@bcts/dcbor\";\nimport {\n SIGNING_PUBLIC_KEY as TAG_SIGNING_PUBLIC_KEY,\n MLDSA_PUBLIC_KEY as TAG_MLDSA_PUBLIC_KEY,\n} from \"@bcts/tags\";\nimport { Ed25519PublicKey } from \"../ed25519/ed25519-public-key.js\";\nimport { Sr25519PublicKey } from \"../sr25519/sr25519-public-key.js\";\nimport { ECPublicKey } from \"../ec-key/ec-public-key.js\";\nimport { SchnorrPublicKey } from \"../ec-key/schnorr-public-key.js\";\nimport { MLDSAPublicKey } from \"../mldsa/mldsa-public-key.js\";\nimport { MLDSALevel } from \"../mldsa/mldsa-level.js\";\nimport { SignatureScheme, isMldsaScheme } from \"./signature-scheme.js\";\nimport type { Signature } from \"./signature.js\";\nimport type { Verifier } from \"./signer.js\";\nimport { Reference, type ReferenceProvider } from \"../reference.js\";\nimport { Digest } from \"../digest.js\";\nimport { UR } from \"@bcts/uniform-resources\";\n\n/**\n * A public key used for verifying digital signatures.\n *\n * Currently supports:\n * - Schnorr public keys (32 bytes, x-only) - bare byte string in CBOR\n * - ECDSA public keys (33 bytes, compressed) - discriminator 1\n * - Ed25519 public keys (32 bytes) - discriminator 2\n * - Sr25519 public keys (32 bytes) - discriminator 3\n * - MLDSA public keys (post-quantum) - tagged CBOR delegating to MLDSAPublicKey\n */\nexport class SigningPublicKey\n implements Verifier, ReferenceProvider, CborTaggedEncodable, CborTaggedDecodable<SigningPublicKey>\n{\n private readonly _type: SignatureScheme;\n private readonly _schnorrKey: SchnorrPublicKey | undefined;\n private readonly _ecdsaKey: ECPublicKey | undefined;\n private readonly _ed25519Key: Ed25519PublicKey | undefined;\n private readonly _sr25519Key: Sr25519PublicKey | undefined;\n private readonly _mldsaKey: MLDSAPublicKey | undefined;\n\n private constructor(\n type: SignatureScheme,\n schnorrKey?: SchnorrPublicKey,\n ecdsaKey?: ECPublicKey,\n ed25519Key?: Ed25519PublicKey,\n sr25519Key?: Sr25519PublicKey,\n mldsaKey?: MLDSAPublicKey,\n ) {\n this._type = type;\n this._schnorrKey = schnorrKey;\n this._ecdsaKey = ecdsaKey;\n this._ed25519Key = ed25519Key;\n this._sr25519Key = sr25519Key;\n this._mldsaKey = mldsaKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Creates a new signing public key from a Schnorr (x-only) public key.\n *\n * @param key - A SchnorrPublicKey\n * @returns A new signing public key containing the Schnorr key\n */\n static fromSchnorr(key: SchnorrPublicKey): SigningPublicKey {\n return new SigningPublicKey(\n SignatureScheme.Schnorr,\n key,\n undefined,\n undefined,\n undefined,\n undefined,\n );\n }\n\n /**\n * Creates a new signing public key from an ECDSA (compressed) public key.\n *\n * @param key - An ECPublicKey\n * @returns A new signing public key containing the ECDSA key\n */\n static fromEcdsa(key: ECPublicKey): SigningPublicKey {\n return new SigningPublicKey(\n SignatureScheme.Ecdsa,\n undefined,\n key,\n undefined,\n undefined,\n undefined,\n );\n }\n\n /**\n * Creates a new signing public key from an Ed25519 public key.\n *\n * @param key - An Ed25519 public key\n * @returns A new signing public key containing the Ed25519 key\n */\n static fromEd25519(key: Ed25519PublicKey): SigningPublicKey {\n return new SigningPublicKey(\n SignatureScheme.Ed25519,\n undefined,\n undefined,\n key,\n undefined,\n undefined,\n );\n }\n\n /**\n * Creates a new signing public key from an Sr25519 public key.\n *\n * @param key - An Sr25519 public key\n * @returns A new signing public key containing the Sr25519 key\n */\n static fromSr25519(key: Sr25519PublicKey): SigningPublicKey {\n return new SigningPublicKey(\n SignatureScheme.Sr25519,\n undefined,\n undefined,\n undefined,\n key,\n undefined,\n );\n }\n\n /**\n * Creates a new signing public key from an MLDSAPublicKey.\n *\n * @param key - An MLDSAPublicKey\n * @returns A new signing public key containing the MLDSA key\n */\n static fromMldsa(key: MLDSAPublicKey): SigningPublicKey {\n // Determine the SignatureScheme based on the MLDSA level\n let scheme: SignatureScheme;\n switch (key.level()) {\n case MLDSALevel.MLDSA44:\n scheme = SignatureScheme.MLDSA44;\n break;\n case MLDSALevel.MLDSA65:\n scheme = SignatureScheme.MLDSA65;\n break;\n case MLDSALevel.MLDSA87:\n scheme = SignatureScheme.MLDSA87;\n break;\n default:\n throw new Error(`Unknown MLDSA level: ${key.level()}`);\n }\n return new SigningPublicKey(scheme, undefined, undefined, undefined, undefined, key);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the signature scheme of this key.\n */\n scheme(): SignatureScheme {\n return this._type;\n }\n\n /**\n * Returns a human-readable string identifying the key type.\n * @returns A string like \"Ed25519\", \"Schnorr\", \"ECDSA\", \"Sr25519\", \"MLDSA-44\", etc.\n */\n keyType(): string {\n switch (this._type) {\n case SignatureScheme.Ed25519:\n return \"Ed25519\";\n case SignatureScheme.Schnorr:\n return \"Schnorr\";\n case SignatureScheme.Ecdsa:\n return \"ECDSA\";\n case SignatureScheme.Sr25519:\n return \"Sr25519\";\n case SignatureScheme.MLDSA44:\n return \"MLDSA-44\";\n case SignatureScheme.MLDSA65:\n return \"MLDSA-65\";\n case SignatureScheme.MLDSA87:\n return \"MLDSA-87\";\n case SignatureScheme.SshEd25519:\n return \"SSH-Ed25519\";\n case SignatureScheme.SshDsa:\n return \"SSH-DSA\";\n case SignatureScheme.SshEcdsaP256:\n return \"SSH-ECDSA-P256\";\n case SignatureScheme.SshEcdsaP384:\n return \"SSH-ECDSA-P384\";\n default:\n return this._type;\n }\n }\n\n /**\n * Returns the underlying Schnorr public key if this is a Schnorr key.\n *\n * @returns The SchnorrPublicKey if this is a Schnorr key, null otherwise\n */\n toSchnorr(): SchnorrPublicKey | null {\n if (this._type === SignatureScheme.Schnorr && this._schnorrKey !== undefined) {\n return this._schnorrKey;\n }\n return null;\n }\n\n /**\n * Returns the underlying ECDSA public key if this is an ECDSA key.\n *\n * @returns The ECPublicKey if this is an ECDSA key, null otherwise\n */\n toEcdsa(): ECPublicKey | null {\n if (this._type === SignatureScheme.Ecdsa && this._ecdsaKey !== undefined) {\n return this._ecdsaKey;\n }\n return null;\n }\n\n /**\n * Returns the underlying Ed25519 public key if this is an Ed25519 key.\n *\n * @returns The Ed25519 public key if this is an Ed25519 key, null otherwise\n */\n toEd25519(): Ed25519PublicKey | null {\n if (this._type === SignatureScheme.Ed25519 && this._ed25519Key !== undefined) {\n return this._ed25519Key;\n }\n return null;\n }\n\n /**\n * Returns the underlying Sr25519 public key if this is an Sr25519 key.\n *\n * @returns The Sr25519 public key if this is an Sr25519 key, null otherwise\n */\n toSr25519(): Sr25519PublicKey | null {\n if (this._type === SignatureScheme.Sr25519 && this._sr25519Key !== undefined) {\n return this._sr25519Key;\n }\n return null;\n }\n\n /**\n * Checks if this is a Schnorr signing key.\n */\n isSchnorr(): boolean {\n return this._type === SignatureScheme.Schnorr;\n }\n\n /**\n * Checks if this is an ECDSA signing key.\n */\n isEcdsa(): boolean {\n return this._type === SignatureScheme.Ecdsa;\n }\n\n /**\n * Checks if this is an Ed25519 signing key.\n */\n isEd25519(): boolean {\n return this._type === SignatureScheme.Ed25519;\n }\n\n /**\n * Checks if this is an Sr25519 signing key.\n */\n isSr25519(): boolean {\n return this._type === SignatureScheme.Sr25519;\n }\n\n /**\n * Returns the underlying MLDSA public key if this is an MLDSA key.\n *\n * @returns The MLDSAPublicKey if this is an MLDSA key, null otherwise\n */\n toMldsa(): MLDSAPublicKey | null {\n if (isMldsaScheme(this._type) && this._mldsaKey !== undefined) {\n return this._mldsaKey;\n }\n return null;\n }\n\n /**\n * Checks if this is an MLDSA signing key.\n */\n isMldsa(): boolean {\n return isMldsaScheme(this._type);\n }\n\n /**\n * Compare with another SigningPublicKey.\n */\n equals(other: SigningPublicKey): boolean {\n if (this._type !== other._type) return false;\n switch (this._type) {\n case SignatureScheme.Schnorr:\n if (this._schnorrKey === undefined || other._schnorrKey === undefined) return false;\n return this._schnorrKey.equals(other._schnorrKey);\n case SignatureScheme.Ecdsa:\n if (this._ecdsaKey === undefined || other._ecdsaKey === undefined) return false;\n return this._ecdsaKey.equals(other._ecdsaKey);\n case SignatureScheme.Ed25519:\n if (this._ed25519Key === undefined || other._ed25519Key === undefined) return false;\n return this._ed25519Key.equals(other._ed25519Key);\n case SignatureScheme.Sr25519:\n if (this._sr25519Key === undefined || other._sr25519Key === undefined) return false;\n return this._sr25519Key.equals(other._sr25519Key);\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87:\n if (this._mldsaKey === undefined || other._mldsaKey === undefined) return false;\n return this._mldsaKey.equals(other._mldsaKey);\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n return false;\n }\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n switch (this._type) {\n case SignatureScheme.Schnorr:\n return `SigningPublicKey(${this._type}, ${this._schnorrKey?.toHex().substring(0, 16)}...)`;\n case SignatureScheme.Ecdsa:\n return `SigningPublicKey(${this._type}, ${this._ecdsaKey?.toHex().substring(0, 16)}...)`;\n case SignatureScheme.Ed25519:\n return `SigningPublicKey(${this._type}, ${this._ed25519Key?.toHex().substring(0, 16)}...)`;\n case SignatureScheme.Sr25519:\n return `SigningPublicKey(${this._type}, ${this._sr25519Key?.toHex().substring(0, 16)}...)`;\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87:\n return `SigningPublicKey(${this._type}, ${this._mldsaKey?.toString().substring(0, 30)}...)`;\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n return `SigningPublicKey(${this._type}, SSH scheme not supported)`;\n }\n }\n\n // ============================================================================\n // ReferenceProvider Interface\n // ============================================================================\n\n /**\n * Returns a unique reference to this SigningPublicKey instance.\n *\n * The reference is derived from the SHA-256 hash of the tagged CBOR\n * representation, providing a unique, content-addressable identifier.\n */\n reference(): Reference {\n const digest = Digest.fromImage(this.taggedCborData());\n return Reference.from(digest);\n }\n\n // ============================================================================\n // Verifier Interface\n // ============================================================================\n\n /**\n * Verifies a signature against a message.\n *\n * @param signature - The signature to verify\n * @param message - The message that was allegedly signed\n * @returns `true` if the signature is valid, `false` otherwise\n */\n verify(signature: Signature, message: Uint8Array): boolean {\n // Check that signature scheme matches\n if (signature.scheme() !== this._type) {\n return false;\n }\n\n switch (this._type) {\n case SignatureScheme.Schnorr: {\n if (this._schnorrKey === undefined) {\n return false;\n }\n const sigData = signature.toSchnorr();\n if (sigData === null) {\n return false;\n }\n try {\n return this._schnorrKey.schnorrVerify(sigData, message);\n } catch {\n return false;\n }\n }\n case SignatureScheme.Ecdsa: {\n if (this._ecdsaKey === undefined) {\n return false;\n }\n const sigData = signature.toEcdsa();\n if (sigData === null) {\n return false;\n }\n try {\n return this._ecdsaKey.verify(sigData, message);\n } catch {\n return false;\n }\n }\n case SignatureScheme.Ed25519: {\n if (this._ed25519Key === undefined) {\n return false;\n }\n const sigData = signature.toEd25519();\n if (sigData === null) {\n return false;\n }\n try {\n return this._ed25519Key.verify(message, sigData);\n } catch {\n return false;\n }\n }\n case SignatureScheme.Sr25519: {\n if (this._sr25519Key === undefined) {\n return false;\n }\n const sigData = signature.toSr25519();\n if (sigData === null) {\n return false;\n }\n try {\n return this._sr25519Key.verify(sigData, message);\n } catch {\n return false;\n }\n }\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87: {\n if (this._mldsaKey === undefined) {\n return false;\n }\n const mldsaSig = signature.toMldsa();\n if (mldsaSig === null) {\n return false;\n }\n try {\n return this._mldsaKey.verify(mldsaSig, message);\n } catch {\n return false;\n }\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n return false;\n }\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with SigningPublicKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SIGNING_PUBLIC_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format (matching Rust bc-components):\n * - Schnorr: h'<32-byte-x-only-public-key>' (bare byte string)\n * - ECDSA: [1, h'<33-byte-compressed-public-key>']\n * - Ed25519: [2, h'<32-byte-public-key>']\n * - Sr25519: [3, h'<32-byte-public-key>']\n */\n untaggedCbor(): Cbor {\n switch (this._type) {\n case SignatureScheme.Schnorr: {\n if (this._schnorrKey === undefined) {\n throw new Error(\"Schnorr public key is missing\");\n }\n // Rust: CBOR::to_byte_string(key.data()) - bare byte string\n return toByteString(this._schnorrKey.toData());\n }\n case SignatureScheme.Ecdsa: {\n if (this._ecdsaKey === undefined) {\n throw new Error(\"ECDSA public key is missing\");\n }\n return cbor([1, toByteString(this._ecdsaKey.toData())]);\n }\n case SignatureScheme.Ed25519: {\n if (this._ed25519Key === undefined) {\n throw new Error(\"Ed25519 public key is missing\");\n }\n return cbor([2, toByteString(this._ed25519Key.toData())]);\n }\n case SignatureScheme.Sr25519: {\n if (this._sr25519Key === undefined) {\n throw new Error(\"Sr25519 public key is missing\");\n }\n return cbor([3, toByteString(this._sr25519Key.toData())]);\n }\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87: {\n if (this._mldsaKey === undefined) {\n throw new Error(\"MLDSA public key is missing\");\n }\n // Rust: delegates to MLDSAPublicKey (which produces tagged CBOR)\n return this._mldsaKey.taggedCbor();\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n throw new Error(`SSH signature scheme ${this._type} is not supported for CBOR encoding`);\n }\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a SigningPublicKey by decoding it from untagged CBOR.\n *\n * Format (matching Rust bc-components):\n * - h'<32-byte-key>' (bare byte string) for Schnorr\n * - [1, h'<33-byte-key>'] for ECDSA\n * - [2, h'<32-byte-key>'] for Ed25519\n * - [3, h'<32-byte-key>'] for Sr25519\n */\n fromUntaggedCbor(cborValue: Cbor): SigningPublicKey {\n // Rust format: Schnorr is a bare byte string\n if (isBytes(cborValue)) {\n const keyData = expectBytes(cborValue);\n return SigningPublicKey.fromSchnorr(SchnorrPublicKey.from(keyData));\n }\n\n // Array format for ECDSA, Ed25519, Sr25519\n if (isArray(cborValue)) {\n const elements = expectArray(cborValue);\n\n if (elements.length !== 2) {\n throw new Error(\"SigningPublicKey array must have 2 elements\");\n }\n\n const discriminator = expectUnsigned(elements[0]);\n const keyData = expectBytes(elements[1]);\n\n switch (Number(discriminator)) {\n case 1: // ECDSA\n return SigningPublicKey.fromEcdsa(ECPublicKey.from(keyData));\n case 2: // Ed25519\n return SigningPublicKey.fromEd25519(Ed25519PublicKey.from(keyData));\n case 3: // Sr25519\n return SigningPublicKey.fromSr25519(Sr25519PublicKey.from(keyData));\n default:\n throw new Error(`Unknown SigningPublicKey discriminator: ${discriminator}`);\n }\n }\n\n // Tagged format for MLDSA\n if (isTagged(cborValue)) {\n const tagged = cborValue.asTagged();\n if (tagged?.[0].value === TAG_MLDSA_PUBLIC_KEY.value) {\n const mldsaKey = MLDSAPublicKey.fromTaggedCbor(cborValue);\n return SigningPublicKey.fromMldsa(mldsaKey);\n }\n }\n\n throw new Error(\n \"SigningPublicKey must be a byte string (Schnorr), array (ECDSA/Ed25519/Sr25519), or tagged MLDSA\",\n );\n }\n\n /**\n * Creates a SigningPublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): SigningPublicKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): SigningPublicKey {\n // Create a dummy instance for accessing instance methods\n const dummy = new SigningPublicKey(\n SignatureScheme.Ed25519,\n undefined, // schnorrKey\n undefined, // ecdsaKey\n Ed25519PublicKey.from(new Uint8Array(ED25519_PUBLIC_KEY_SIZE)), // ed25519Key\n );\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): SigningPublicKey {\n const cborValue = decodeCbor(data);\n return SigningPublicKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): SigningPublicKey {\n const cborValue = decodeCbor(data);\n const dummy = new SigningPublicKey(\n SignatureScheme.Ed25519,\n undefined, // schnorrKey\n undefined, // ecdsaKey\n Ed25519PublicKey.from(new Uint8Array(ED25519_PUBLIC_KEY_SIZE)), // ed25519Key\n );\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR (Uniform Resource) Serialization\n // ============================================================================\n\n /**\n * Get the UR type for signing public keys.\n */\n static readonly UR_TYPE = \"signing-public-key\";\n\n /**\n * Returns the UR representation of the signing public key.\n */\n ur(): UR {\n return UR.new(SigningPublicKey.UR_TYPE, this.taggedCbor());\n }\n\n /**\n * Returns the UR string representation of the signing public key.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a SigningPublicKey from a UR.\n */\n static fromUR(ur: UR): SigningPublicKey {\n ur.checkType(SigningPublicKey.UR_TYPE);\n return SigningPublicKey.fromTaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a SigningPublicKey from a UR string.\n */\n static fromURString(urString: string): SigningPublicKey {\n const ur = UR.fromURString(urString);\n return SigningPublicKey.fromUR(ur);\n }\n\n /**\n * Alias for fromURString for Rust API compatibility.\n */\n static fromUrString(urString: string): SigningPublicKey {\n return SigningPublicKey.fromURString(urString);\n }\n\n // ============================================================================\n // SSH Format\n // ============================================================================\n\n /**\n * Converts the public key to SSH format.\n * Currently only supports Ed25519 keys.\n */\n toSsh(comment?: string): string {\n if (this._type !== SignatureScheme.Ed25519) {\n throw new Error(`SSH export only supports Ed25519 keys, got ${this._type}`);\n }\n if (this._ed25519Key === undefined) {\n throw new Error(\"Ed25519 key not initialized\");\n }\n\n // SSH format: ssh-ed25519 <base64-encoded-data> [comment]\n // The data is: 4-byte length of \"ssh-ed25519\" + \"ssh-ed25519\" + 4-byte length of key + key bytes\n const algorithm = \"ssh-ed25519\";\n const algorithmBytes = new TextEncoder().encode(algorithm);\n const keyBytes = this._ed25519Key.toData();\n const keyLen = keyBytes.length;\n\n // Build the blob: [4-byte length][algorithm][4-byte length][key]\n const totalLength = 4 + algorithmBytes.length + 4 + keyLen;\n const blob = new Uint8Array(totalLength);\n let offset = 0;\n\n // Write algorithm length (big-endian)\n blob[offset++] = (algorithmBytes.length >> 24) & 0xff;\n blob[offset++] = (algorithmBytes.length >> 16) & 0xff;\n blob[offset++] = (algorithmBytes.length >> 8) & 0xff;\n blob[offset++] = algorithmBytes.length & 0xff;\n\n // Write algorithm\n blob.set(algorithmBytes, offset);\n offset += algorithmBytes.length;\n\n // Write key length (big-endian)\n blob[offset++] = (keyLen >> 24) & 0xff;\n blob[offset++] = (keyLen >> 16) & 0xff;\n blob[offset++] = (keyLen >> 8) & 0xff;\n blob[offset++] = keyLen & 0xff;\n\n // Write key\n blob.set(keyBytes, offset);\n\n // Base64 encode the blob\n let base64 = \"\";\n const bytes = blob;\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n for (let i = 0; i < bytes.length; i += 3) {\n const b0 = bytes[i];\n const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;\n const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;\n base64 += chars[(b0 >> 2) & 0x3f];\n base64 += chars[((b0 << 4) | (b1 >> 4)) & 0x3f];\n base64 += i + 1 < bytes.length ? chars[((b1 << 2) | (b2 >> 6)) & 0x3f] : \"=\";\n base64 += i + 2 < bytes.length ? chars[b2 & 0x3f] : \"=\";\n }\n\n const result = `${algorithm} ${base64}`;\n return comment !== undefined && comment !== \"\" ? `${result} ${comment}` : result;\n }\n}\n","/**\n * A private key used for creating digital signatures.\n *\n * `SigningPrivateKey` is a type representing different types of signing\n * private keys. Supports Schnorr, ECDSA, Ed25519, and SR25519.\n *\n * This type implements the `Signer` interface, allowing it to create signatures.\n *\n * # CBOR Serialization\n *\n * `SigningPrivateKey` is serialized to CBOR with tag 40021.\n *\n * The CBOR encoding (matching Rust bc-components):\n * - Schnorr: `#6.40021(h'<32-byte-private-key>')` (bare byte string)\n * - ECDSA: `#6.40021([1, h'<32-byte-private-key>'])`\n * - Ed25519: `#6.40021([2, h'<32-byte-private-key>'])`\n * - SR25519: `#6.40021([3, h'<32-byte-seed>'])`\n *\n * Ported from bc-components-rust/src/signing/signing_private_key.rs\n */\n\nimport { ED25519_PRIVATE_KEY_SIZE } from \"@bcts/crypto\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectArray,\n expectBytes,\n expectUnsigned,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n isBytes,\n isArray,\n isTagged,\n} from \"@bcts/dcbor\";\nimport {\n SIGNING_PRIVATE_KEY as TAG_SIGNING_PRIVATE_KEY,\n MLDSA_PRIVATE_KEY as TAG_MLDSA_PRIVATE_KEY,\n} from \"@bcts/tags\";\nimport { Ed25519PrivateKey } from \"../ed25519/ed25519-private-key.js\";\nimport { Sr25519PrivateKey } from \"../sr25519/sr25519-private-key.js\";\nimport { ECPrivateKey } from \"../ec-key/ec-private-key.js\";\nimport { MLDSAPrivateKey } from \"../mldsa/mldsa-private-key.js\";\nimport { MLDSALevel } from \"../mldsa/mldsa-level.js\";\nimport { SignatureScheme, isMldsaScheme, type SigningOptions } from \"./signature-scheme.js\";\nimport { Signature } from \"./signature.js\";\nimport { SigningPublicKey } from \"./signing-public-key.js\";\nimport type { Signer, Verifier } from \"./signer.js\";\nimport { Reference, type ReferenceProvider } from \"../reference.js\";\nimport { Digest } from \"../digest.js\";\nimport { UR } from \"@bcts/uniform-resources\";\n\n/**\n * A private key used for creating digital signatures.\n *\n * Currently supports:\n * - Schnorr private keys (32 bytes, secp256k1) - bare byte string in CBOR\n * - ECDSA private keys (32 bytes, secp256k1) - discriminator 1\n * - Ed25519 private keys (32 bytes) - discriminator 2\n * - SR25519 private keys (32-byte seed) - discriminator 3\n * - MLDSA private keys (post-quantum) - tagged CBOR delegating to MLDSAPrivateKey\n */\nexport class SigningPrivateKey\n implements\n Signer,\n Verifier,\n ReferenceProvider,\n CborTaggedEncodable,\n CborTaggedDecodable<SigningPrivateKey>\n{\n private readonly _type: SignatureScheme;\n private readonly _ecKey: ECPrivateKey | undefined;\n private readonly _ed25519Key: Ed25519PrivateKey | undefined;\n private readonly _sr25519Key: Sr25519PrivateKey | undefined;\n private readonly _mldsaKey: MLDSAPrivateKey | undefined;\n\n private constructor(\n type: SignatureScheme,\n ecKey?: ECPrivateKey,\n ed25519Key?: Ed25519PrivateKey,\n sr25519Key?: Sr25519PrivateKey,\n mldsaKey?: MLDSAPrivateKey,\n ) {\n this._type = type;\n this._ecKey = ecKey;\n this._ed25519Key = ed25519Key;\n this._sr25519Key = sr25519Key;\n this._mldsaKey = mldsaKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Creates a new Schnorr signing private key from an ECPrivateKey.\n *\n * @param key - The EC private key to use for Schnorr signing\n * @returns A new Schnorr signing private key\n */\n static newSchnorr(key: ECPrivateKey): SigningPrivateKey {\n return new SigningPrivateKey(SignatureScheme.Schnorr, key, undefined, undefined, undefined);\n }\n\n /**\n * Creates a new ECDSA signing private key from an ECPrivateKey.\n *\n * @param key - The EC private key to use for ECDSA signing\n * @returns A new ECDSA signing private key\n */\n static newEcdsa(key: ECPrivateKey): SigningPrivateKey {\n return new SigningPrivateKey(SignatureScheme.Ecdsa, key, undefined, undefined, undefined);\n }\n\n /**\n * Creates a new Ed25519 signing private key from an Ed25519PrivateKey.\n *\n * @param key - The Ed25519 private key to use\n * @returns A new Ed25519 signing private key\n */\n static newEd25519(key: Ed25519PrivateKey): SigningPrivateKey {\n return new SigningPrivateKey(SignatureScheme.Ed25519, undefined, key, undefined, undefined);\n }\n\n /**\n * Creates a new SR25519 signing private key from an Sr25519PrivateKey.\n *\n * @param key - The SR25519 private key to use\n * @returns A new SR25519 signing private key\n */\n static newSr25519(key: Sr25519PrivateKey): SigningPrivateKey {\n return new SigningPrivateKey(SignatureScheme.Sr25519, undefined, undefined, key, undefined);\n }\n\n /**\n * Creates a new MLDSA signing private key from an MLDSAPrivateKey.\n *\n * @param key - The MLDSA private key to use\n * @returns A new MLDSA signing private key\n */\n static newMldsa(key: MLDSAPrivateKey): SigningPrivateKey {\n // Determine the SignatureScheme based on the MLDSA level\n let scheme: SignatureScheme;\n switch (key.level()) {\n case MLDSALevel.MLDSA44:\n scheme = SignatureScheme.MLDSA44;\n break;\n case MLDSALevel.MLDSA65:\n scheme = SignatureScheme.MLDSA65;\n break;\n case MLDSALevel.MLDSA87:\n scheme = SignatureScheme.MLDSA87;\n break;\n default:\n throw new Error(`Unknown MLDSA level: ${key.level()}`);\n }\n return new SigningPrivateKey(scheme, undefined, undefined, undefined, key);\n }\n\n /**\n * Creates a new random Ed25519 signing private key.\n *\n * @returns A new random Ed25519 signing private key\n */\n static random(): SigningPrivateKey {\n return SigningPrivateKey.newEd25519(Ed25519PrivateKey.random());\n }\n\n /**\n * Creates a new random Schnorr signing private key.\n *\n * @returns A new random Schnorr signing private key\n */\n static randomSchnorr(): SigningPrivateKey {\n return SigningPrivateKey.newSchnorr(ECPrivateKey.random());\n }\n\n /**\n * Creates a new random ECDSA signing private key.\n *\n * @returns A new random ECDSA signing private key\n */\n static randomEcdsa(): SigningPrivateKey {\n return SigningPrivateKey.newEcdsa(ECPrivateKey.random());\n }\n\n /**\n * Creates a new random SR25519 signing private key.\n *\n * @returns A new random SR25519 signing private key\n */\n static randomSr25519(): SigningPrivateKey {\n return SigningPrivateKey.newSr25519(Sr25519PrivateKey.random());\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the signature scheme of this key.\n */\n scheme(): SignatureScheme {\n return this._type;\n }\n\n /**\n * Returns a human-readable string identifying the key type.\n * @returns A string like \"Ed25519\", \"Schnorr\", \"ECDSA\", \"Sr25519\", \"MLDSA-44\", etc.\n */\n keyType(): string {\n switch (this._type) {\n case SignatureScheme.Ed25519:\n return \"Ed25519\";\n case SignatureScheme.Schnorr:\n return \"Schnorr\";\n case SignatureScheme.Ecdsa:\n return \"ECDSA\";\n case SignatureScheme.Sr25519:\n return \"Sr25519\";\n case SignatureScheme.MLDSA44:\n return \"MLDSA-44\";\n case SignatureScheme.MLDSA65:\n return \"MLDSA-65\";\n case SignatureScheme.MLDSA87:\n return \"MLDSA-87\";\n case SignatureScheme.SshEd25519:\n return \"SSH-Ed25519\";\n case SignatureScheme.SshDsa:\n return \"SSH-DSA\";\n case SignatureScheme.SshEcdsaP256:\n return \"SSH-ECDSA-P256\";\n case SignatureScheme.SshEcdsaP384:\n return \"SSH-ECDSA-P384\";\n default:\n return this._type;\n }\n }\n\n /**\n * Returns the underlying EC private key if this is a Schnorr or ECDSA key.\n *\n * @returns The EC private key if this is a Schnorr or ECDSA key, null otherwise\n */\n toEc(): ECPrivateKey | null {\n if (\n (this._type === SignatureScheme.Schnorr || this._type === SignatureScheme.Ecdsa) &&\n this._ecKey !== undefined\n ) {\n return this._ecKey;\n }\n return null;\n }\n\n /**\n * Returns the underlying Schnorr private key if this is a Schnorr key.\n *\n * @returns The EC private key if this is a Schnorr key, null otherwise\n */\n toSchnorr(): ECPrivateKey | null {\n if (this._type === SignatureScheme.Schnorr && this._ecKey !== undefined) {\n return this._ecKey;\n }\n return null;\n }\n\n /**\n * Returns the underlying ECDSA private key if this is an ECDSA key.\n *\n * @returns The EC private key if this is an ECDSA key, null otherwise\n */\n toEcdsa(): ECPrivateKey | null {\n if (this._type === SignatureScheme.Ecdsa && this._ecKey !== undefined) {\n return this._ecKey;\n }\n return null;\n }\n\n /**\n * Returns the underlying Ed25519 private key if this is an Ed25519 key.\n *\n * @returns The Ed25519 private key if this is an Ed25519 key, null otherwise\n */\n toEd25519(): Ed25519PrivateKey | null {\n if (this._type === SignatureScheme.Ed25519 && this._ed25519Key !== undefined) {\n return this._ed25519Key;\n }\n return null;\n }\n\n /**\n * Returns the underlying Sr25519 private key if this is an Sr25519 key.\n *\n * @returns The Sr25519 private key if this is an Sr25519 key, null otherwise\n */\n toSr25519(): Sr25519PrivateKey | null {\n if (this._type === SignatureScheme.Sr25519 && this._sr25519Key !== undefined) {\n return this._sr25519Key;\n }\n return null;\n }\n\n /**\n * Returns the underlying MLDSA private key if this is an MLDSA key.\n *\n * @returns The MLDSA private key if this is an MLDSA key, null otherwise\n */\n toMldsa(): MLDSAPrivateKey | null {\n if (isMldsaScheme(this._type) && this._mldsaKey !== undefined) {\n return this._mldsaKey;\n }\n return null;\n }\n\n /**\n * Checks if this is a Schnorr signing key.\n */\n isSchnorr(): boolean {\n return this._type === SignatureScheme.Schnorr;\n }\n\n /**\n * Checks if this is an ECDSA signing key.\n */\n isEcdsa(): boolean {\n return this._type === SignatureScheme.Ecdsa;\n }\n\n /**\n * Checks if this is an Ed25519 signing key.\n */\n isEd25519(): boolean {\n return this._type === SignatureScheme.Ed25519;\n }\n\n /**\n * Checks if this is an Sr25519 signing key.\n */\n isSr25519(): boolean {\n return this._type === SignatureScheme.Sr25519;\n }\n\n /**\n * Checks if this is an MLDSA signing key.\n */\n isMldsa(): boolean {\n return isMldsaScheme(this._type);\n }\n\n /**\n * Derives the corresponding public key for this private key.\n *\n * @returns The public key corresponding to this private key\n */\n publicKey(): SigningPublicKey {\n switch (this._type) {\n case SignatureScheme.Schnorr: {\n if (this._ecKey === undefined) {\n throw new Error(\"EC private key is missing\");\n }\n return SigningPublicKey.fromSchnorr(this._ecKey.schnorrPublicKey());\n }\n case SignatureScheme.Ecdsa: {\n if (this._ecKey === undefined) {\n throw new Error(\"EC private key is missing\");\n }\n return SigningPublicKey.fromEcdsa(this._ecKey.publicKey());\n }\n case SignatureScheme.Ed25519: {\n if (this._ed25519Key === undefined) {\n throw new Error(\"Ed25519 private key is missing\");\n }\n return SigningPublicKey.fromEd25519(this._ed25519Key.publicKey());\n }\n case SignatureScheme.Sr25519: {\n if (this._sr25519Key === undefined) {\n throw new Error(\"Sr25519 private key is missing\");\n }\n return SigningPublicKey.fromSr25519(this._sr25519Key.publicKey());\n }\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87: {\n if (this._mldsaKey === undefined) {\n throw new Error(\"MLDSA private key is missing\");\n }\n return SigningPublicKey.fromMldsa(this._mldsaKey.publicKey());\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n throw new Error(`SSH signature scheme ${this._type} is not supported`);\n }\n }\n\n /**\n * Compare with another SigningPrivateKey.\n */\n equals(other: SigningPrivateKey): boolean {\n if (this._type !== other._type) return false;\n switch (this._type) {\n case SignatureScheme.Schnorr:\n case SignatureScheme.Ecdsa:\n if (this._ecKey === undefined || other._ecKey === undefined) return false;\n return this._ecKey.equals(other._ecKey);\n case SignatureScheme.Ed25519:\n if (this._ed25519Key === undefined || other._ed25519Key === undefined) return false;\n return this._ed25519Key.equals(other._ed25519Key);\n case SignatureScheme.Sr25519:\n if (this._sr25519Key === undefined || other._sr25519Key === undefined) return false;\n return this._sr25519Key.equals(other._sr25519Key);\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87:\n if (this._mldsaKey === undefined || other._mldsaKey === undefined) return false;\n return this._mldsaKey.equals(other._mldsaKey);\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n return false;\n }\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `SigningPrivateKey(${this._type})`;\n }\n\n // ============================================================================\n // ReferenceProvider Interface\n // ============================================================================\n\n /**\n * Returns a unique reference to this SigningPrivateKey instance.\n *\n * The reference is derived from the SHA-256 hash of the tagged CBOR\n * representation, providing a unique, content-addressable identifier.\n */\n reference(): Reference {\n const digest = Digest.fromImage(this.taggedCborData());\n return Reference.from(digest);\n }\n\n // ============================================================================\n // Signer Interface\n // ============================================================================\n\n /**\n * Signs a message with optional signing options.\n *\n * Different signature schemes may use the options differently:\n * - Schnorr: Can accept a custom random number generator via SigningOptions.Schnorr\n * - SSH: Would require namespace and hash algorithm (not yet implemented)\n * - Other schemes (ECDSA, Ed25519, Sr25519, MLDSA): Options are ignored\n *\n * @param message - The message to sign\n * @param options - Optional signing options\n * @returns The digital signature\n */\n signWithOptions(message: Uint8Array, options?: SigningOptions): Signature {\n switch (this._type) {\n case SignatureScheme.Schnorr: {\n if (this._ecKey === undefined) {\n throw new Error(\"EC private key is missing\");\n }\n // If Schnorr options with custom RNG are provided, use them\n if (options?.type === \"Schnorr\") {\n const sigData = this._ecKey.schnorrSignUsing(message, options.rng);\n return Signature.schnorrFromData(sigData);\n }\n // Otherwise use default RNG\n const sigData = this._ecKey.schnorrSign(message);\n return Signature.schnorrFromData(sigData);\n }\n case SignatureScheme.Ecdsa: {\n if (this._ecKey === undefined) {\n throw new Error(\"EC private key is missing\");\n }\n const sigData = this._ecKey.ecdsaSign(message);\n return Signature.ecdsaFromData(sigData);\n }\n case SignatureScheme.Ed25519: {\n if (this._ed25519Key === undefined) {\n throw new Error(\"Ed25519 private key is missing\");\n }\n const sigData = this._ed25519Key.sign(message);\n return Signature.ed25519FromData(sigData);\n }\n case SignatureScheme.Sr25519: {\n if (this._sr25519Key === undefined) {\n throw new Error(\"Sr25519 private key is missing\");\n }\n const sigData = this._sr25519Key.sign(message);\n return Signature.sr25519FromData(sigData);\n }\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87: {\n if (this._mldsaKey === undefined) {\n throw new Error(\"MLDSA private key is missing\");\n }\n const mldsaSig = this._mldsaKey.sign(message);\n return Signature.mldsaFromSignature(mldsaSig);\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n // SSH signing requires SigningOptions.Ssh with namespace and hash algorithm\n if (options?.type === \"Ssh\") {\n throw new Error(\n `SSH signature scheme ${this._type} is not yet implemented. ` +\n `Namespace: ${options.namespace}, hashAlg: ${options.hashAlg}`,\n );\n }\n throw new Error(`SSH signature scheme ${this._type} requires SigningOptions.Ssh`);\n }\n }\n\n /**\n * Signs a message using default options.\n *\n * This is a convenience method that calls `signWithOptions` with no options.\n *\n * @param message - The message to sign\n * @returns The digital signature\n */\n sign(message: Uint8Array): Signature {\n return this.signWithOptions(message);\n }\n\n // ============================================================================\n // Verifier Interface\n // ============================================================================\n\n /**\n * Verifies a signature against a message.\n *\n * @param signature - The signature to verify\n * @param message - The message that was allegedly signed\n * @returns `true` if the signature is valid, `false` otherwise\n */\n verify(signature: Signature, message: Uint8Array): boolean {\n return this.publicKey().verify(signature, message);\n }\n\n // ============================================================================\n // Scheme-Specific Sign Methods\n // ============================================================================\n\n /**\n * Signs a message using Schnorr with the provided random number generator.\n *\n * This method is only valid for Schnorr keys.\n *\n * @param message - The message to sign\n * @param rng - The random number generator to use for signature creation\n * @returns The Schnorr signature\n * @throws Error if this is not a Schnorr key\n */\n schnorrSign(message: Uint8Array, rng: RandomNumberGenerator): Signature {\n const privateKey = this.toSchnorr();\n if (privateKey === null) {\n throw new Error(\"Invalid key type for Schnorr signing\");\n }\n const sigData = privateKey.schnorrSignUsing(message, rng);\n return Signature.schnorrFromData(sigData);\n }\n\n /**\n * Signs a message using ECDSA.\n *\n * This method is only valid for ECDSA keys.\n *\n * @param message - The message to sign\n * @returns The ECDSA signature\n * @throws Error if this is not an ECDSA key\n */\n ecdsaSign(message: Uint8Array): Signature {\n const privateKey = this.toEcdsa();\n if (privateKey === null) {\n throw new Error(\"Invalid key type for ECDSA signing\");\n }\n const sigData = privateKey.ecdsaSign(message);\n return Signature.ecdsaFromData(sigData);\n }\n\n /**\n * Signs a message using Ed25519.\n *\n * This method is only valid for Ed25519 keys.\n *\n * @param message - The message to sign\n * @returns The Ed25519 signature\n * @throws Error if this is not an Ed25519 key\n */\n ed25519Sign(message: Uint8Array): Signature {\n const privateKey = this.toEd25519();\n if (privateKey === null) {\n throw new Error(\"Invalid key type for Ed25519 signing\");\n }\n const sigData = privateKey.sign(message);\n return Signature.ed25519FromData(sigData);\n }\n\n /**\n * Signs a message using SR25519.\n *\n * This method is only valid for SR25519 keys.\n *\n * @param message - The message to sign\n * @returns The SR25519 signature\n * @throws Error if this is not an SR25519 key\n */\n sr25519Sign(message: Uint8Array): Signature {\n const privateKey = this.toSr25519();\n if (privateKey === null) {\n throw new Error(\"Invalid key type for SR25519 signing\");\n }\n const sigData = privateKey.sign(message);\n return Signature.sr25519FromData(sigData);\n }\n\n /**\n * Signs a message using ML-DSA.\n *\n * This method is only valid for MLDSA keys.\n *\n * @param message - The message to sign\n * @returns The ML-DSA signature\n * @throws Error if this is not an MLDSA key\n */\n mldsaSign(message: Uint8Array): Signature {\n const privateKey = this.toMldsa();\n if (privateKey === null) {\n throw new Error(\"Invalid key type for MLDSA signing\");\n }\n const mldsaSig = privateKey.sign(message);\n return Signature.mldsaFromSignature(mldsaSig);\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with SigningPrivateKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SIGNING_PRIVATE_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format (matching Rust bc-components):\n * - Schnorr: h'<32-byte-private-key>' (bare byte string)\n * - ECDSA: [1, h'<32-byte-private-key>']\n * - Ed25519: [2, h'<32-byte-private-key>']\n * - Sr25519: [3, h'<32-byte-seed>']\n * - MLDSA: delegates to MLDSAPrivateKey (tagged)\n */\n untaggedCbor(): Cbor {\n switch (this._type) {\n case SignatureScheme.Schnorr: {\n if (this._ecKey === undefined) {\n throw new Error(\"EC private key is missing\");\n }\n // Rust: CBOR::to_byte_string(key.data()) - bare byte string\n return toByteString(this._ecKey.toData());\n }\n case SignatureScheme.Ecdsa: {\n if (this._ecKey === undefined) {\n throw new Error(\"EC private key is missing\");\n }\n return cbor([1, toByteString(this._ecKey.toData())]);\n }\n case SignatureScheme.Ed25519: {\n if (this._ed25519Key === undefined) {\n throw new Error(\"Ed25519 private key is missing\");\n }\n return cbor([2, toByteString(this._ed25519Key.toData())]);\n }\n case SignatureScheme.Sr25519: {\n if (this._sr25519Key === undefined) {\n throw new Error(\"Sr25519 private key is missing\");\n }\n return cbor([3, toByteString(this._sr25519Key.toData())]);\n }\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87: {\n if (this._mldsaKey === undefined) {\n throw new Error(\"MLDSA private key is missing\");\n }\n // Rust: delegates to MLDSAPrivateKey (which produces tagged CBOR)\n return this._mldsaKey.taggedCbor();\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n throw new Error(`SSH signature scheme ${this._type} is not supported for CBOR encoding`);\n }\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a SigningPrivateKey by decoding it from untagged CBOR.\n *\n * Format (matching Rust bc-components):\n * - h'<32-byte-key>' (bare byte string) for Schnorr\n * - [1, h'<32-byte-key>'] for ECDSA\n * - [2, h'<32-byte-key>'] for Ed25519\n * - [3, h'<32-byte-seed>'] for Sr25519\n * - tagged MLDSA private key for MLDSA variants\n */\n fromUntaggedCbor(cborValue: Cbor): SigningPrivateKey {\n // Rust format: Schnorr is a bare byte string\n if (isBytes(cborValue)) {\n const keyData = expectBytes(cborValue);\n return SigningPrivateKey.newSchnorr(ECPrivateKey.from(keyData));\n }\n\n // Array format for ECDSA, Ed25519, Sr25519\n if (isArray(cborValue)) {\n const elements = expectArray(cborValue);\n\n if (elements.length !== 2) {\n throw new Error(\"SigningPrivateKey array must have 2 elements\");\n }\n\n const discriminator = expectUnsigned(elements[0]);\n const keyData = expectBytes(elements[1]);\n\n switch (Number(discriminator)) {\n case 1: // ECDSA\n return SigningPrivateKey.newEcdsa(ECPrivateKey.from(keyData));\n case 2: // Ed25519\n return SigningPrivateKey.newEd25519(Ed25519PrivateKey.from(keyData));\n case 3: // Sr25519\n return SigningPrivateKey.newSr25519(Sr25519PrivateKey.from(keyData));\n default:\n throw new Error(`Unknown SigningPrivateKey discriminator: ${discriminator}`);\n }\n }\n\n // Tagged format for MLDSA\n if (isTagged(cborValue)) {\n const tagged = cborValue.asTagged();\n if (tagged?.[0].value === TAG_MLDSA_PRIVATE_KEY.value) {\n const mldsaKey = MLDSAPrivateKey.fromTaggedCbor(cborValue);\n return SigningPrivateKey.newMldsa(mldsaKey);\n }\n }\n\n throw new Error(\n \"SigningPrivateKey must be a byte string (Schnorr), array (ECDSA/Ed25519/Sr25519), or tagged MLDSA\",\n );\n }\n\n /**\n * Creates a SigningPrivateKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): SigningPrivateKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): SigningPrivateKey {\n // Create a dummy instance for accessing instance methods\n const dummy = new SigningPrivateKey(\n SignatureScheme.Ed25519,\n undefined, // ecKey\n Ed25519PrivateKey.from(new Uint8Array(ED25519_PRIVATE_KEY_SIZE)), // ed25519Key\n );\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): SigningPrivateKey {\n const cborValue = decodeCbor(data);\n return SigningPrivateKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): SigningPrivateKey {\n const cborValue = decodeCbor(data);\n const dummy = new SigningPrivateKey(\n SignatureScheme.Ed25519,\n undefined, // ecKey\n Ed25519PrivateKey.from(new Uint8Array(ED25519_PRIVATE_KEY_SIZE)), // ed25519Key\n );\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR (Uniform Resource) Serialization\n // ============================================================================\n\n /**\n * Get the UR type for signing private keys.\n */\n static readonly UR_TYPE = \"signing-private-key\";\n\n /**\n * Returns the UR representation of the signing private key.\n */\n ur(): UR {\n return UR.new(SigningPrivateKey.UR_TYPE, this.taggedCbor());\n }\n\n /**\n * Returns the UR string representation of the signing private key.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a SigningPrivateKey from a UR.\n */\n static fromUR(ur: UR): SigningPrivateKey {\n ur.checkType(SigningPrivateKey.UR_TYPE);\n return SigningPrivateKey.fromTaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a SigningPrivateKey from a UR string.\n */\n static fromURString(urString: string): SigningPrivateKey {\n const ur = UR.fromURString(urString);\n return SigningPrivateKey.fromUR(ur);\n }\n\n /**\n * Alias for fromURString for Rust API compatibility.\n */\n static fromUrString(urString: string): SigningPrivateKey {\n return SigningPrivateKey.fromURString(urString);\n }\n\n // ============================================================================\n // SSH Format\n // ============================================================================\n\n /**\n * Converts the private key to OpenSSH format.\n * Currently only supports Ed25519 keys.\n */\n toSsh(comment?: string): string {\n if (this._type !== SignatureScheme.Ed25519) {\n throw new Error(`SSH export only supports Ed25519 keys, got ${this._type}`);\n }\n if (this._ed25519Key === undefined) {\n throw new Error(\"Ed25519 key not initialized\");\n }\n\n // OpenSSH private key format for Ed25519\n\n const publicKey = this._ed25519Key.publicKey();\n const privateKeyBytes = this._ed25519Key.toData();\n const publicKeyBytes = publicKey.toData();\n\n // For OpenSSH Ed25519, the \"private key\" is actually the 64-byte concatenation of:\n // - 32-byte seed (the actual private key)\n // - 32-byte public key\n const combinedKey = new Uint8Array(64);\n combinedKey.set(privateKeyBytes, 0);\n combinedKey.set(publicKeyBytes, 32);\n\n // Build the OpenSSH private key format (simplified version)\n const algorithm = \"ssh-ed25519\";\n const checkInt = Math.floor(Math.random() * 0xffffffff);\n const checkIntBytes = new Uint8Array(4);\n checkIntBytes[0] = (checkInt >> 24) & 0xff;\n checkIntBytes[1] = (checkInt >> 16) & 0xff;\n checkIntBytes[2] = (checkInt >> 8) & 0xff;\n checkIntBytes[3] = checkInt & 0xff;\n\n // This is a simplified implementation - in practice you'd need bcrypt_pbkdf\n // and proper key wrapping. For now, return a placeholder format.\n const actualComment = comment ?? \"\";\n return `-----BEGIN OPENSSH PRIVATE KEY-----\nPlaceholder for ${algorithm} private key export (${actualComment})\nThis requires bcrypt_pbkdf implementation for proper encryption.\n-----END OPENSSH PRIVATE KEY-----`;\n }\n}\n","/**\n * Supported digital signature schemes.\n *\n * This enum represents the various signature schemes supported in this crate,\n * including Ed25519, SR25519, ECDSA, Schnorr, post-quantum ML-DSA, and SSH-based signatures.\n *\n * Ported from bc-components-rust/src/signing/signature_scheme.rs\n */\n\nimport { type SecureRandomNumberGenerator, type RandomNumberGenerator } from \"@bcts/rand\";\nimport { Ed25519PrivateKey } from \"../ed25519/ed25519-private-key.js\";\nimport { Sr25519PrivateKey } from \"../sr25519/sr25519-private-key.js\";\nimport { ECPrivateKey } from \"../ec-key/ec-private-key.js\";\nimport { MLDSAPrivateKey } from \"../mldsa/mldsa-private-key.js\";\nimport { MLDSALevel } from \"../mldsa/mldsa-level.js\";\nimport { SigningPrivateKey } from \"./signing-private-key.js\";\nimport type { SigningPublicKey } from \"./signing-public-key.js\";\nimport { CryptoError } from \"../error.js\";\n\n/**\n * Supported digital signature schemes.\n *\n * This enum represents the various signature schemes supported in this package.\n * - Schnorr: BIP-340 Schnorr signature scheme (secp256k1) - DEFAULT\n * - ECDSA: ECDSA signature scheme (secp256k1)\n * - Ed25519: RFC 8032 signatures\n * - Sr25519: Schnorr over Ristretto25519, used by Polkadot/Substrate\n * - MLDSA44: ML-DSA44 post-quantum signature scheme (NIST level 2)\n * - MLDSA65: ML-DSA65 post-quantum signature scheme (NIST level 3)\n * - MLDSA87: ML-DSA87 post-quantum signature scheme (NIST level 5)\n * - SshEd25519: Ed25519 via SSH agent\n * - SshDsa: DSA via SSH agent\n * - SshEcdsaP256: ECDSA P-256 via SSH agent\n * - SshEcdsaP384: ECDSA P-384 via SSH agent\n */\nexport enum SignatureScheme {\n /**\n * BIP-340 Schnorr signature scheme (secp256k1)\n * Default scheme (matching Rust bc-components default when secp256k1 is enabled)\n */\n Schnorr = \"Schnorr\",\n\n /**\n * ECDSA signature scheme (secp256k1)\n */\n Ecdsa = \"Ecdsa\",\n\n /**\n * Ed25519 signature scheme (RFC 8032)\n */\n Ed25519 = \"Ed25519\",\n\n /**\n * SR25519 signature scheme (Schnorr over Ristretto25519)\n * Used by Polkadot/Substrate\n */\n Sr25519 = \"Sr25519\",\n\n /**\n * ML-DSA44 post-quantum signature scheme (NIST level 2)\n */\n MLDSA44 = \"MLDSA44\",\n\n /**\n * ML-DSA65 post-quantum signature scheme (NIST level 3)\n */\n MLDSA65 = \"MLDSA65\",\n\n /**\n * ML-DSA87 post-quantum signature scheme (NIST level 5)\n */\n MLDSA87 = \"MLDSA87\",\n\n /**\n * Ed25519 signature via SSH agent.\n * Requires SSH agent daemon support.\n */\n SshEd25519 = \"SshEd25519\",\n\n /**\n * DSA signature via SSH agent.\n * Requires SSH agent daemon support.\n */\n SshDsa = \"SshDsa\",\n\n /**\n * ECDSA P-256 signature via SSH agent.\n * Requires SSH agent daemon support.\n */\n SshEcdsaP256 = \"SshEcdsaP256\",\n\n /**\n * ECDSA P-384 signature via SSH agent.\n * Requires SSH agent daemon support.\n */\n SshEcdsaP384 = \"SshEcdsaP384\",\n}\n\n/**\n * Get the default signature scheme.\n * Defaults to Schnorr (matching Rust bc-components default when secp256k1 is enabled).\n */\nexport function defaultSignatureScheme(): SignatureScheme {\n return SignatureScheme.Schnorr;\n}\n\n/**\n * Check if a signature scheme requires SSH agent support.\n *\n * @param scheme - The signature scheme to check\n * @returns true if the scheme requires SSH agent\n */\nexport function isSshScheme(scheme: SignatureScheme): boolean {\n return (\n scheme === SignatureScheme.SshEd25519 ||\n scheme === SignatureScheme.SshDsa ||\n scheme === SignatureScheme.SshEcdsaP256 ||\n scheme === SignatureScheme.SshEcdsaP384\n );\n}\n\n/**\n * Check if a signature scheme is a post-quantum ML-DSA scheme.\n *\n * @param scheme - The signature scheme to check\n * @returns true if the scheme is an ML-DSA scheme\n */\nexport function isMldsaScheme(scheme: SignatureScheme): boolean {\n return (\n scheme === SignatureScheme.MLDSA44 ||\n scheme === SignatureScheme.MLDSA65 ||\n scheme === SignatureScheme.MLDSA87\n );\n}\n\n/**\n * Options for configuring signature creation.\n *\n * Different signature schemes may require specific options:\n * - Schnorr: Optionally accepts a custom random number generator\n * - Ssh: Requires a namespace and hash algorithm\n *\n * Other signature types like ECDSA, Ed25519, Sr25519, and ML-DSA don't require options.\n */\nexport type SigningOptions =\n | {\n type: \"Schnorr\";\n /** Custom random number generator for signature creation */\n rng: RandomNumberGenerator;\n }\n | {\n type: \"Ssh\";\n /** The namespace used for SSH signatures */\n namespace: string;\n /** The hash algorithm used for SSH signatures */\n hashAlg: \"sha256\" | \"sha512\";\n };\n\n/**\n * Creates a new key pair for the signature scheme.\n *\n * @param scheme - The signature scheme to use\n * @returns A tuple containing a signing private key and its corresponding public key\n * @throws CryptoError for SSH-based schemes which require SSH agent support\n */\nexport function createKeypair(scheme: SignatureScheme): [SigningPrivateKey, SigningPublicKey] {\n switch (scheme) {\n case SignatureScheme.Schnorr: {\n const ecKey = ECPrivateKey.random();\n const privateKey = SigningPrivateKey.newSchnorr(ecKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.Ecdsa: {\n const ecKey = ECPrivateKey.random();\n const privateKey = SigningPrivateKey.newEcdsa(ecKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.Ed25519: {\n const ed25519Key = Ed25519PrivateKey.random();\n const privateKey = SigningPrivateKey.newEd25519(ed25519Key);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.Sr25519: {\n const sr25519Key = Sr25519PrivateKey.random();\n const privateKey = SigningPrivateKey.newSr25519(sr25519Key);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.MLDSA44: {\n const mldsaKey = MLDSAPrivateKey.new(MLDSALevel.MLDSA44);\n const privateKey = SigningPrivateKey.newMldsa(mldsaKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.MLDSA65: {\n const mldsaKey = MLDSAPrivateKey.new(MLDSALevel.MLDSA65);\n const privateKey = SigningPrivateKey.newMldsa(mldsaKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.MLDSA87: {\n const mldsaKey = MLDSAPrivateKey.new(MLDSALevel.MLDSA87);\n const privateKey = SigningPrivateKey.newMldsa(mldsaKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n throw CryptoError.sshAgent(\n `SSH signature scheme ${scheme} requires SSH agent support which is not yet implemented. ` +\n \"Use Ed25519, Sr25519, Schnorr, ECDSA, or MLDSA variants instead.\",\n );\n }\n}\n\n/**\n * Creates a new key pair for the signature scheme using a provided RNG.\n *\n * @param scheme - The signature scheme to use\n * @param rng - The random number generator to use\n * @returns A tuple containing a signing private key and its corresponding public key\n * @throws CryptoError for SSH-based schemes or MLDSA (which doesn't support deterministic generation)\n */\nexport function createKeypairUsing(\n scheme: SignatureScheme,\n rng: SecureRandomNumberGenerator,\n): [SigningPrivateKey, SigningPublicKey] {\n switch (scheme) {\n case SignatureScheme.Schnorr: {\n const ecKey = ECPrivateKey.newUsing(rng);\n const privateKey = SigningPrivateKey.newSchnorr(ecKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.Ecdsa: {\n const ecKey = ECPrivateKey.newUsing(rng);\n const privateKey = SigningPrivateKey.newEcdsa(ecKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.Ed25519: {\n const ed25519Key = Ed25519PrivateKey.randomUsing(rng);\n const privateKey = SigningPrivateKey.newEd25519(ed25519Key);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.Sr25519: {\n const sr25519Key = Sr25519PrivateKey.randomUsing(rng);\n const privateKey = SigningPrivateKey.newSr25519(sr25519Key);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87:\n // ML-DSA doesn't support deterministic generation with custom RNG (matching Rust behavior)\n throw CryptoError.general(\n `Deterministic keypair generation not supported for ${scheme}. Use createKeypair() instead.`,\n );\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n throw CryptoError.sshAgent(\n `SSH signature scheme ${scheme} requires SSH agent support which is not yet implemented. ` +\n \"Use Ed25519, Sr25519, Schnorr, ECDSA, or MLDSA variants instead.\",\n );\n }\n}\n","/**\n * MLKEM Security Level - ML-KEM (Module-Lattice-Based Key Encapsulation Mechanism)\n *\n * ML-KEM is a post-quantum key encapsulation mechanism standardized by NIST.\n * It provides three security levels corresponding to different NIST security categories.\n *\n * Security levels:\n * - MLKEM512: NIST Level 1 (equivalent to AES-128)\n * - MLKEM768: NIST Level 3 (equivalent to AES-192)\n * - MLKEM1024: NIST Level 5 (equivalent to AES-256)\n *\n * Ported from bc-components-rust/src/mlkem/mlkem_level.rs\n */\n\nimport { ml_kem512, ml_kem768, ml_kem1024 } from \"@noble/post-quantum/ml-kem.js\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\n\n/**\n * ML-KEM security levels.\n *\n * The numeric values correspond to the ML-KEM parameter set:\n * - 512: ML-KEM-512 (NIST Level 1)\n * - 768: ML-KEM-768 (NIST Level 3)\n * - 1024: ML-KEM-1024 (NIST Level 5)\n */\nexport enum MLKEMLevel {\n /** NIST Level 1 - AES-128 equivalent security */\n MLKEM512 = 512,\n /** NIST Level 3 - AES-192 equivalent security */\n MLKEM768 = 768,\n /** NIST Level 5 - AES-256 equivalent security */\n MLKEM1024 = 1024,\n}\n\n/**\n * Key sizes for each ML-KEM security level.\n */\nexport const MLKEM_KEY_SIZES = {\n [MLKEMLevel.MLKEM512]: {\n privateKey: 1632,\n publicKey: 800,\n ciphertext: 768,\n sharedSecret: 32,\n },\n [MLKEMLevel.MLKEM768]: {\n privateKey: 2400,\n publicKey: 1184,\n ciphertext: 1088,\n sharedSecret: 32,\n },\n [MLKEMLevel.MLKEM1024]: {\n privateKey: 3168,\n publicKey: 1568,\n ciphertext: 1568,\n sharedSecret: 32,\n },\n} as const;\n\n/**\n * Get the private key size for a given ML-KEM level.\n */\nexport function mlkemPrivateKeySize(level: MLKEMLevel): number {\n return MLKEM_KEY_SIZES[level].privateKey;\n}\n\n/**\n * Get the public key size for a given ML-KEM level.\n */\nexport function mlkemPublicKeySize(level: MLKEMLevel): number {\n return MLKEM_KEY_SIZES[level].publicKey;\n}\n\n/**\n * Get the ciphertext size for a given ML-KEM level.\n */\nexport function mlkemCiphertextSize(level: MLKEMLevel): number {\n return MLKEM_KEY_SIZES[level].ciphertext;\n}\n\n/**\n * Get the shared secret size for a given ML-KEM level.\n * Note: This is always 32 bytes for all ML-KEM levels.\n */\nexport function mlkemSharedSecretSize(level: MLKEMLevel): number {\n return MLKEM_KEY_SIZES[level].sharedSecret;\n}\n\n/**\n * Convert an ML-KEM level to its string representation.\n */\nexport function mlkemLevelToString(level: MLKEMLevel): string {\n switch (level) {\n case MLKEMLevel.MLKEM512:\n return \"MLKEM512\";\n case MLKEMLevel.MLKEM768:\n return \"MLKEM768\";\n case MLKEMLevel.MLKEM1024:\n return \"MLKEM1024\";\n }\n}\n\n/**\n * Parse an ML-KEM level from its numeric value.\n */\nexport function mlkemLevelFromValue(value: number): MLKEMLevel {\n switch (value) {\n case 512:\n return MLKEMLevel.MLKEM512;\n case 768:\n return MLKEMLevel.MLKEM768;\n case 1024:\n return MLKEMLevel.MLKEM1024;\n default:\n throw new Error(`Invalid MLKEM level value: ${value}`);\n }\n}\n\n/**\n * Internal type for ML-KEM keypair generation result.\n */\nexport interface MLKEMKeypairData {\n publicKey: Uint8Array;\n secretKey: Uint8Array;\n}\n\n/**\n * Internal type for ML-KEM encapsulation result.\n */\nexport interface MLKEMEncapsulationResult {\n sharedSecret: Uint8Array;\n ciphertext: Uint8Array;\n}\n\n/**\n * Generate an ML-KEM keypair for the given security level.\n *\n * @param level - The ML-KEM security level\n * @returns Object containing publicKey and secretKey bytes\n */\nexport function mlkemGenerateKeypair(level: MLKEMLevel): MLKEMKeypairData {\n const rng = new SecureRandomNumberGenerator();\n return mlkemGenerateKeypairUsing(level, rng);\n}\n\n/**\n * Generate an ML-KEM keypair using a provided RNG.\n *\n * @param level - The ML-KEM security level\n * @param rng - Random number generator\n * @returns Object containing publicKey and secretKey bytes\n */\nexport function mlkemGenerateKeypairUsing(\n level: MLKEMLevel,\n rng: RandomNumberGenerator,\n): MLKEMKeypairData {\n // Generate random seed for keypair generation\n const seed = rng.randomData(64);\n\n switch (level) {\n case MLKEMLevel.MLKEM512: {\n const keypair = ml_kem512.keygen(seed);\n return { publicKey: keypair.publicKey, secretKey: keypair.secretKey };\n }\n case MLKEMLevel.MLKEM768: {\n const keypair = ml_kem768.keygen(seed);\n return { publicKey: keypair.publicKey, secretKey: keypair.secretKey };\n }\n case MLKEMLevel.MLKEM1024: {\n const keypair = ml_kem1024.keygen(seed);\n return { publicKey: keypair.publicKey, secretKey: keypair.secretKey };\n }\n }\n}\n\n/**\n * Encapsulate a new shared secret using a public key.\n *\n * @param level - The ML-KEM security level\n * @param publicKey - The public key bytes\n * @returns Object containing sharedSecret and ciphertext bytes\n */\nexport function mlkemEncapsulate(\n level: MLKEMLevel,\n publicKey: Uint8Array,\n): MLKEMEncapsulationResult {\n switch (level) {\n case MLKEMLevel.MLKEM512: {\n const result = ml_kem512.encapsulate(publicKey);\n return { sharedSecret: result.sharedSecret, ciphertext: result.cipherText };\n }\n case MLKEMLevel.MLKEM768: {\n const result = ml_kem768.encapsulate(publicKey);\n return { sharedSecret: result.sharedSecret, ciphertext: result.cipherText };\n }\n case MLKEMLevel.MLKEM1024: {\n const result = ml_kem1024.encapsulate(publicKey);\n return { sharedSecret: result.sharedSecret, ciphertext: result.cipherText };\n }\n }\n}\n\n/**\n * Decapsulate a shared secret using a private key and ciphertext.\n *\n * @param level - The ML-KEM security level\n * @param secretKey - The secret key bytes\n * @param ciphertext - The ciphertext bytes\n * @returns The shared secret bytes\n */\nexport function mlkemDecapsulate(\n level: MLKEMLevel,\n secretKey: Uint8Array,\n ciphertext: Uint8Array,\n): Uint8Array {\n switch (level) {\n case MLKEMLevel.MLKEM512:\n return ml_kem512.decapsulate(ciphertext, secretKey);\n case MLKEMLevel.MLKEM768:\n return ml_kem768.decapsulate(ciphertext, secretKey);\n case MLKEMLevel.MLKEM1024:\n return ml_kem1024.decapsulate(ciphertext, secretKey);\n }\n}\n\n/**\n * Private key portion sizes for each ML-KEM level.\n * The decapsulation key structure is: dk = (dk_pke || ek_pke || H(ek) || z)\n * where dk_pke is the private portion before the public key.\n */\nconst MLKEM_DK_PKE_SIZES = {\n [MLKEMLevel.MLKEM512]: 768, // 12 * 64\n [MLKEMLevel.MLKEM768]: 1152, // 12 * 96\n [MLKEMLevel.MLKEM1024]: 1536, // 12 * 128\n} as const;\n\n/**\n * Extract the public key from a secret key.\n *\n * In ML-KEM (FIPS 203), the decapsulation key contains the encapsulation key (public key)\n * embedded within it. The structure is: dk = (dk_pke || ek_pke || H(ek) || z)\n *\n * @param level - The ML-KEM security level\n * @param secretKey - The secret key bytes\n * @returns The public key bytes extracted from the secret key\n */\nexport function mlkemExtractPublicKey(level: MLKEMLevel, secretKey: Uint8Array): Uint8Array {\n const dkPkeSize = MLKEM_DK_PKE_SIZES[level];\n const publicKeySize = MLKEM_KEY_SIZES[level].publicKey;\n const offset = dkPkeSize;\n return secretKey.slice(offset, offset + publicKeySize);\n}\n","/**\n * MLKEMCiphertext - ML-KEM Ciphertext for post-quantum key encapsulation\n *\n * MLKEMCiphertext wraps an ML-KEM ciphertext for transmission and decapsulation.\n * It supports all three security levels (MLKEM512, MLKEM768, MLKEM1024).\n *\n * # CBOR Serialization\n *\n * MLKEMCiphertext is serialized with tag 40102:\n * ```\n * #6.40102([level, h'<ciphertext-bytes>'])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `mlkem-ciphertext`\n *\n * Ported from bc-components-rust/src/mlkem/mlkem_ciphertext.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n expectInteger,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { MLKEM_CIPHERTEXT as TAG_MLKEM_CIPHERTEXT } from \"@bcts/tags\";\n\nimport {\n MLKEMLevel,\n mlkemLevelFromValue,\n mlkemLevelToString,\n mlkemCiphertextSize,\n} from \"./mlkem-level.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * MLKEMCiphertext - Post-quantum key encapsulation ciphertext using ML-KEM.\n */\nexport class MLKEMCiphertext\n implements CborTaggedEncodable, CborTaggedDecodable<MLKEMCiphertext>, UREncodable\n{\n private readonly _level: MLKEMLevel;\n private readonly _data: Uint8Array;\n\n private constructor(level: MLKEMLevel, data: Uint8Array) {\n const expectedSize = mlkemCiphertextSize(level);\n if (data.length !== expectedSize) {\n throw new Error(\n `MLKEMCiphertext (${mlkemLevelToString(level)}) must be ${expectedSize} bytes, got ${data.length}`,\n );\n }\n this._level = level;\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an MLKEMCiphertext from raw bytes.\n *\n * @param level - The ML-KEM security level\n * @param data - The ciphertext bytes\n */\n static fromBytes(level: MLKEMLevel, data: Uint8Array): MLKEMCiphertext {\n return new MLKEMCiphertext(level, data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the security level of this ciphertext.\n */\n level(): MLKEMLevel {\n return this._level;\n }\n\n /**\n * Returns the raw ciphertext bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw ciphertext bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the size of the ciphertext in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another MLKEMCiphertext.\n */\n equals(other: MLKEMCiphertext): boolean {\n if (this._level !== other._level) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `MLKEMCiphertext(${mlkemLevelToString(this._level)}, ${hex.substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with MLKEMCiphertext.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_MLKEM_CIPHERTEXT.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [level, ciphertext_bytes]\n */\n untaggedCbor(): Cbor {\n return cbor([this._level, this._data]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an MLKEMCiphertext by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): MLKEMCiphertext {\n const elements = expectArray(cborValue);\n if (elements.length !== 2) {\n throw new Error(`MLKEMCiphertext CBOR must have 2 elements, got ${elements.length}`);\n }\n const levelValue = Number(expectInteger(elements[0]));\n const level = mlkemLevelFromValue(levelValue);\n const data = expectBytes(elements[1]);\n return MLKEMCiphertext.fromBytes(level, data);\n }\n\n /**\n * Creates an MLKEMCiphertext by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): MLKEMCiphertext {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): MLKEMCiphertext {\n // Create a minimal dummy instance for decoding\n const dummyData = new Uint8Array(mlkemCiphertextSize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMCiphertext(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): MLKEMCiphertext {\n const cborValue = decodeCbor(data);\n return MLKEMCiphertext.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): MLKEMCiphertext {\n const cborValue = decodeCbor(data);\n const dummyData = new Uint8Array(mlkemCiphertextSize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMCiphertext(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_MLKEM_CIPHERTEXT.name;\n if (name === undefined) {\n throw new Error(\"MLKEM_CIPHERTEXT tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an MLKEMCiphertext from a UR.\n */\n static fromUR(ur: UR): MLKEMCiphertext {\n if (ur.urTypeStr() !== TAG_MLKEM_CIPHERTEXT.name) {\n throw new Error(`Expected UR type ${TAG_MLKEM_CIPHERTEXT.name}, got ${ur.urTypeStr()}`);\n }\n const dummyData = new Uint8Array(mlkemCiphertextSize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMCiphertext(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an MLKEMCiphertext from a UR string.\n */\n static fromURString(urString: string): MLKEMCiphertext {\n const ur = UR.fromURString(urString);\n return MLKEMCiphertext.fromUR(ur);\n }\n}\n","/**\n * Encapsulation ciphertext for key encapsulation mechanisms\n *\n * This type represents the ciphertext produced during key encapsulation.\n * For X25519, this is actually an ephemeral public key used in ECDH.\n * For MLKEM, this is the ciphertext from the ML-KEM encapsulation.\n *\n * # CBOR Serialization\n *\n * For X25519, the ciphertext is serialized with the X25519 public key tag (40011).\n * For MLKEM, the ciphertext is serialized with tag 40102.\n *\n * Ported from bc-components-rust/src/encapsulation/encapsulation_ciphertext.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n tagValue,\n} from \"@bcts/dcbor\";\nimport {\n X25519_PUBLIC_KEY as TAG_X25519_PUBLIC_KEY,\n MLKEM_CIPHERTEXT as TAG_MLKEM_CIPHERTEXT,\n} from \"@bcts/tags\";\nimport { X25519PublicKey } from \"../x25519/x25519-public-key.js\";\nimport { EncapsulationScheme } from \"./encapsulation-scheme.js\";\nimport { MLKEMCiphertext } from \"../mlkem/mlkem-ciphertext.js\";\nimport { MLKEMLevel } from \"../mlkem/mlkem-level.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * Convert MLKEMLevel to EncapsulationScheme\n */\nfunction mlkemLevelToScheme(level: MLKEMLevel): EncapsulationScheme {\n switch (level) {\n case MLKEMLevel.MLKEM512:\n return EncapsulationScheme.MLKEM512;\n case MLKEMLevel.MLKEM768:\n return EncapsulationScheme.MLKEM768;\n case MLKEMLevel.MLKEM1024:\n return EncapsulationScheme.MLKEM1024;\n }\n}\n\n/**\n * Check if a scheme is an MLKEM scheme\n */\nfunction isMlkemScheme(scheme: EncapsulationScheme): boolean {\n return (\n scheme === EncapsulationScheme.MLKEM512 ||\n scheme === EncapsulationScheme.MLKEM768 ||\n scheme === EncapsulationScheme.MLKEM1024\n );\n}\n\n/**\n * Represents the ciphertext from a key encapsulation operation.\n *\n * For X25519, this wraps an ephemeral public key.\n * For MLKEM, this wraps an MLKEMCiphertext.\n */\nexport class EncapsulationCiphertext\n implements CborTaggedEncodable, CborTaggedDecodable<EncapsulationCiphertext>\n{\n private readonly _scheme: EncapsulationScheme;\n private readonly _x25519PublicKey: X25519PublicKey | undefined;\n private readonly _mlkemCiphertext: MLKEMCiphertext | undefined;\n\n private constructor(\n scheme: EncapsulationScheme,\n x25519PublicKey?: X25519PublicKey,\n mlkemCiphertext?: MLKEMCiphertext,\n ) {\n this._scheme = scheme;\n this._x25519PublicKey = x25519PublicKey;\n this._mlkemCiphertext = mlkemCiphertext;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an EncapsulationCiphertext from an X25519PublicKey.\n */\n static fromX25519PublicKey(publicKey: X25519PublicKey): EncapsulationCiphertext {\n return new EncapsulationCiphertext(EncapsulationScheme.X25519, publicKey, undefined);\n }\n\n /**\n * Create an EncapsulationCiphertext from raw X25519 data.\n */\n static fromX25519Data(data: Uint8Array): EncapsulationCiphertext {\n const publicKey = X25519PublicKey.fromDataRef(data);\n return EncapsulationCiphertext.fromX25519PublicKey(publicKey);\n }\n\n /**\n * Create an EncapsulationCiphertext from an MLKEMCiphertext.\n */\n static fromMlkem(ciphertext: MLKEMCiphertext): EncapsulationCiphertext {\n const scheme = mlkemLevelToScheme(ciphertext.level());\n return new EncapsulationCiphertext(scheme, undefined, ciphertext);\n }\n\n /**\n * Create an EncapsulationCiphertext from raw MLKEM ciphertext bytes.\n */\n static fromMlkemData(level: MLKEMLevel, data: Uint8Array): EncapsulationCiphertext {\n const ciphertext = MLKEMCiphertext.fromBytes(level, data);\n return EncapsulationCiphertext.fromMlkem(ciphertext);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the encapsulation scheme.\n */\n encapsulationScheme(): EncapsulationScheme {\n return this._scheme;\n }\n\n /**\n * Returns true if this is an X25519 ciphertext.\n */\n isX25519(): boolean {\n return this._scheme === EncapsulationScheme.X25519;\n }\n\n /**\n * Returns true if this is an MLKEM ciphertext.\n */\n isMlkem(): boolean {\n return isMlkemScheme(this._scheme);\n }\n\n /**\n * Returns the X25519 public key if this is an X25519 ciphertext.\n * @throws Error if this is not an X25519 ciphertext\n */\n x25519PublicKey(): X25519PublicKey {\n if (this._x25519PublicKey === undefined) {\n throw new Error(\"Not an X25519 ciphertext\");\n }\n return this._x25519PublicKey;\n }\n\n /**\n * Returns the MLKEM ciphertext if this is an MLKEM ciphertext.\n * @throws Error if this is not an MLKEM ciphertext\n */\n mlkemCiphertext(): MLKEMCiphertext {\n if (this._mlkemCiphertext === undefined) {\n throw new Error(\"Not an MLKEM ciphertext\");\n }\n return this._mlkemCiphertext;\n }\n\n /**\n * Returns the X25519 public key if available, or null.\n */\n toX25519(): X25519PublicKey | null {\n return this._x25519PublicKey ?? null;\n }\n\n /**\n * Returns the MLKEM ciphertext if available, or null.\n */\n toMlkem(): MLKEMCiphertext | null {\n return this._mlkemCiphertext ?? null;\n }\n\n /**\n * Returns the raw ciphertext data.\n */\n data(): Uint8Array {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PublicKey;\n if (pk === undefined) throw new Error(\"X25519 public key not set\");\n return pk.data();\n } else if (isMlkemScheme(this._scheme)) {\n const ct = this._mlkemCiphertext;\n if (ct === undefined) throw new Error(\"MLKEM ciphertext not set\");\n return ct.data();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Compare with another EncapsulationCiphertext.\n */\n equals(other: EncapsulationCiphertext): boolean {\n if (this._scheme !== other._scheme) return false;\n if (this._scheme === EncapsulationScheme.X25519) {\n const thisPk = this._x25519PublicKey;\n const otherPk = other._x25519PublicKey;\n if (thisPk === undefined || otherPk === undefined) return false;\n return thisPk.equals(otherPk);\n } else if (isMlkemScheme(this._scheme)) {\n const thisCt = this._mlkemCiphertext;\n const otherCt = other._mlkemCiphertext;\n if (thisCt === undefined || otherCt === undefined) return false;\n return thisCt.equals(otherCt);\n }\n return false;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n if (this._scheme === EncapsulationScheme.X25519) {\n return `EncapsulationCiphertext(X25519, ${bytesToHex(this.data()).substring(0, 16)}...)`;\n } else if (isMlkemScheme(this._scheme)) {\n return `EncapsulationCiphertext(${String(this._scheme)}, ${bytesToHex(this.data()).substring(0, 16)}...)`;\n }\n return `EncapsulationCiphertext(${String(this._scheme)})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with this ciphertext.\n */\n cborTags(): Tag[] {\n if (this._scheme === EncapsulationScheme.X25519) {\n return tagsForValues([TAG_X25519_PUBLIC_KEY.value]);\n } else if (isMlkemScheme(this._scheme)) {\n return tagsForValues([TAG_MLKEM_CIPHERTEXT.value]);\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n */\n untaggedCbor(): Cbor {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PublicKey;\n if (pk === undefined) throw new Error(\"X25519 public key not set\");\n return toByteString(pk.data());\n } else if (isMlkemScheme(this._scheme)) {\n const ct = this._mlkemCiphertext;\n if (ct === undefined) throw new Error(\"MLKEM ciphertext not set\");\n return ct.untaggedCbor();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an EncapsulationCiphertext by decoding it from untagged CBOR.\n * Note: Without tags, we assume X25519 scheme.\n */\n fromUntaggedCbor(cborValue: Cbor): EncapsulationCiphertext {\n const data = expectBytes(cborValue);\n const publicKey = X25519PublicKey.fromDataRef(data);\n return EncapsulationCiphertext.fromX25519PublicKey(publicKey);\n }\n\n /**\n * Creates an EncapsulationCiphertext by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): EncapsulationCiphertext {\n const tag = tagValue(cborValue);\n\n if (tag === TAG_X25519_PUBLIC_KEY.value) {\n const content = extractTaggedContent(cborValue);\n const data = expectBytes(content);\n const publicKey = X25519PublicKey.fromDataRef(data);\n return EncapsulationCiphertext.fromX25519PublicKey(publicKey);\n }\n\n if (tag === TAG_MLKEM_CIPHERTEXT.value) {\n const mlkemCiphertext = MLKEMCiphertext.fromTaggedCbor(cborValue);\n return EncapsulationCiphertext.fromMlkem(mlkemCiphertext);\n }\n\n throw new Error(`Unknown ciphertext tag: ${tag}`);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): EncapsulationCiphertext {\n const dummy = EncapsulationCiphertext.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): EncapsulationCiphertext {\n const cborValue = decodeCbor(data);\n return EncapsulationCiphertext.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): EncapsulationCiphertext {\n const cborValue = decodeCbor(data);\n const dummy = EncapsulationCiphertext.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromUntaggedCbor(cborValue);\n }\n}\n","/**\n * MLKEMPublicKey - ML-KEM Public Key for post-quantum key encapsulation\n *\n * MLKEMPublicKey wraps an ML-KEM public key for encapsulating shared secrets.\n * It supports all three security levels (MLKEM512, MLKEM768, MLKEM1024).\n *\n * # CBOR Serialization\n *\n * MLKEMPublicKey is serialized with tag 40101:\n * ```\n * #6.40101([level, h'<public-key-bytes>'])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `mlkem-public-key`\n *\n * Ported from bc-components-rust/src/mlkem/mlkem_public_key.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n expectInteger,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { MLKEM_PUBLIC_KEY as TAG_MLKEM_PUBLIC_KEY } from \"@bcts/tags\";\n\nimport {\n MLKEMLevel,\n mlkemLevelFromValue,\n mlkemLevelToString,\n mlkemPublicKeySize,\n mlkemEncapsulate,\n} from \"./mlkem-level.js\";\nimport { MLKEMCiphertext } from \"./mlkem-ciphertext.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * Result of encapsulation operation.\n */\nexport interface MLKEMEncapsulationPair {\n /** The shared secret as a SymmetricKey */\n sharedSecret: SymmetricKey;\n /** The ciphertext to send to the private key holder */\n ciphertext: MLKEMCiphertext;\n}\n\n/**\n * MLKEMPublicKey - Post-quantum key encapsulation public key using ML-KEM.\n */\nexport class MLKEMPublicKey\n implements CborTaggedEncodable, CborTaggedDecodable<MLKEMPublicKey>, UREncodable\n{\n private readonly _level: MLKEMLevel;\n private readonly _data: Uint8Array;\n\n private constructor(level: MLKEMLevel, data: Uint8Array) {\n const expectedSize = mlkemPublicKeySize(level);\n if (data.length !== expectedSize) {\n throw new Error(\n `MLKEMPublicKey (${mlkemLevelToString(level)}) must be ${expectedSize} bytes, got ${data.length}`,\n );\n }\n this._level = level;\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an MLKEMPublicKey from raw bytes.\n *\n * @param level - The ML-KEM security level\n * @param data - The public key bytes\n */\n static fromBytes(level: MLKEMLevel, data: Uint8Array): MLKEMPublicKey {\n return new MLKEMPublicKey(level, data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the security level of this key.\n */\n level(): MLKEMLevel {\n return this._level;\n }\n\n /**\n * Returns the raw key bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw key bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the size of the key in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n /**\n * Encapsulate a new shared secret.\n *\n * This creates a random shared secret and encapsulates it, returning both\n * the shared secret (to be used as a symmetric key) and the ciphertext\n * (to be sent to the private key holder for decapsulation).\n *\n * @returns Object containing sharedSecret and ciphertext\n */\n encapsulate(): MLKEMEncapsulationPair {\n const result = mlkemEncapsulate(this._level, this._data);\n const sharedSecret = SymmetricKey.fromData(result.sharedSecret);\n const ciphertext = MLKEMCiphertext.fromBytes(this._level, result.ciphertext);\n return { sharedSecret, ciphertext };\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another MLKEMPublicKey.\n */\n equals(other: MLKEMPublicKey): boolean {\n if (this._level !== other._level) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `MLKEMPublicKey(${mlkemLevelToString(this._level)}, ${hex.substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with MLKEMPublicKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_MLKEM_PUBLIC_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [level, key_bytes]\n */\n untaggedCbor(): Cbor {\n return cbor([this._level, this._data]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an MLKEMPublicKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): MLKEMPublicKey {\n const elements = expectArray(cborValue);\n if (elements.length !== 2) {\n throw new Error(`MLKEMPublicKey CBOR must have 2 elements, got ${elements.length}`);\n }\n const levelValue = Number(expectInteger(elements[0]));\n const level = mlkemLevelFromValue(levelValue);\n const data = expectBytes(elements[1]);\n return MLKEMPublicKey.fromBytes(level, data);\n }\n\n /**\n * Creates an MLKEMPublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): MLKEMPublicKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): MLKEMPublicKey {\n // Create a minimal dummy instance for decoding\n const dummyData = new Uint8Array(mlkemPublicKeySize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMPublicKey(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): MLKEMPublicKey {\n const cborValue = decodeCbor(data);\n return MLKEMPublicKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): MLKEMPublicKey {\n const cborValue = decodeCbor(data);\n const dummyData = new Uint8Array(mlkemPublicKeySize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMPublicKey(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_MLKEM_PUBLIC_KEY.name;\n if (name === undefined) {\n throw new Error(\"MLKEM_PUBLIC_KEY tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an MLKEMPublicKey from a UR.\n */\n static fromUR(ur: UR): MLKEMPublicKey {\n if (ur.urTypeStr() !== TAG_MLKEM_PUBLIC_KEY.name) {\n throw new Error(`Expected UR type ${TAG_MLKEM_PUBLIC_KEY.name}, got ${ur.urTypeStr()}`);\n }\n const dummyData = new Uint8Array(mlkemPublicKeySize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMPublicKey(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an MLKEMPublicKey from a UR string.\n */\n static fromURString(urString: string): MLKEMPublicKey {\n const ur = UR.fromURString(urString);\n return MLKEMPublicKey.fromUR(ur);\n }\n}\n","/**\n * Encapsulation public key for key encapsulation mechanisms\n *\n * This type represents a public key that can be used to encapsulate (encrypt)\n * a shared secret. The recipient can then use their corresponding private key\n * to decapsulate (decrypt) the shared secret.\n *\n * For X25519, encapsulation works by:\n * 1. Generating an ephemeral key pair\n * 2. Performing ECDH with the ephemeral private key and the recipient's public key\n * 3. Returning the shared secret and the ephemeral public key as \"ciphertext\"\n *\n * For MLKEM, encapsulation uses the ML-KEM algorithm to generate a shared secret\n * and ciphertext.\n *\n * # CBOR Serialization\n *\n * For X25519, the public key is serialized with tag 40011.\n * For MLKEM, the public key is serialized with tag 40101.\n *\n * Ported from bc-components-rust/src/encapsulation/encapsulation_public_key.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n tagValue,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport {\n X25519_PUBLIC_KEY as TAG_X25519_PUBLIC_KEY,\n MLKEM_PUBLIC_KEY as TAG_MLKEM_PUBLIC_KEY,\n} from \"@bcts/tags\";\nimport { X25519PrivateKey } from \"../x25519/x25519-private-key.js\";\nimport { X25519PublicKey } from \"../x25519/x25519-public-key.js\";\nimport { type SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { EncapsulationScheme } from \"./encapsulation-scheme.js\";\nimport { EncapsulationCiphertext } from \"./encapsulation-ciphertext.js\";\nimport { MLKEMPublicKey } from \"../mlkem/mlkem-public-key.js\";\nimport { MLKEMLevel } from \"../mlkem/mlkem-level.js\";\nimport { bytesToHex } from \"../utils.js\";\nimport { Reference, type ReferenceProvider } from \"../reference.js\";\nimport { Digest } from \"../digest.js\";\n\n/**\n * Convert MLKEMLevel to EncapsulationScheme\n */\nfunction mlkemLevelToScheme(level: MLKEMLevel): EncapsulationScheme {\n switch (level) {\n case MLKEMLevel.MLKEM512:\n return EncapsulationScheme.MLKEM512;\n case MLKEMLevel.MLKEM768:\n return EncapsulationScheme.MLKEM768;\n case MLKEMLevel.MLKEM1024:\n return EncapsulationScheme.MLKEM1024;\n }\n}\n\n/**\n * Check if a scheme is an MLKEM scheme\n */\nfunction isMlkemScheme(scheme: EncapsulationScheme): boolean {\n return (\n scheme === EncapsulationScheme.MLKEM512 ||\n scheme === EncapsulationScheme.MLKEM768 ||\n scheme === EncapsulationScheme.MLKEM1024\n );\n}\n\n/**\n * Represents a public key for key encapsulation.\n *\n * Use this to encapsulate a shared secret for a recipient.\n */\nexport class EncapsulationPublicKey\n implements\n ReferenceProvider,\n CborTaggedEncodable,\n CborTaggedDecodable<EncapsulationPublicKey>,\n UREncodable\n{\n private readonly _scheme: EncapsulationScheme;\n private readonly _x25519PublicKey: X25519PublicKey | undefined;\n private readonly _mlkemPublicKey: MLKEMPublicKey | undefined;\n\n private constructor(\n scheme: EncapsulationScheme,\n x25519PublicKey?: X25519PublicKey,\n mlkemPublicKey?: MLKEMPublicKey,\n ) {\n this._scheme = scheme;\n this._x25519PublicKey = x25519PublicKey;\n this._mlkemPublicKey = mlkemPublicKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an EncapsulationPublicKey from an X25519PublicKey.\n */\n static fromX25519PublicKey(publicKey: X25519PublicKey): EncapsulationPublicKey {\n return new EncapsulationPublicKey(EncapsulationScheme.X25519, publicKey, undefined);\n }\n\n /**\n * Create an EncapsulationPublicKey from raw X25519 public key bytes.\n */\n static fromX25519Data(data: Uint8Array): EncapsulationPublicKey {\n const publicKey = X25519PublicKey.fromDataRef(data);\n return EncapsulationPublicKey.fromX25519PublicKey(publicKey);\n }\n\n /**\n * Create an EncapsulationPublicKey from an MLKEMPublicKey.\n */\n static fromMlkem(publicKey: MLKEMPublicKey): EncapsulationPublicKey {\n const scheme = mlkemLevelToScheme(publicKey.level());\n return new EncapsulationPublicKey(scheme, undefined, publicKey);\n }\n\n /**\n * Create an EncapsulationPublicKey from raw MLKEM public key bytes.\n */\n static fromMlkemData(level: MLKEMLevel, data: Uint8Array): EncapsulationPublicKey {\n const publicKey = MLKEMPublicKey.fromBytes(level, data);\n return EncapsulationPublicKey.fromMlkem(publicKey);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the encapsulation scheme.\n */\n encapsulationScheme(): EncapsulationScheme {\n return this._scheme;\n }\n\n /**\n * Returns true if this is an X25519 public key.\n */\n isX25519(): boolean {\n return this._scheme === EncapsulationScheme.X25519;\n }\n\n /**\n * Returns true if this is an MLKEM public key.\n */\n isMlkem(): boolean {\n return isMlkemScheme(this._scheme);\n }\n\n /**\n * Returns the X25519 public key if this is an X25519 encapsulation key.\n * @throws Error if this is not an X25519 key\n */\n x25519PublicKey(): X25519PublicKey {\n if (this._x25519PublicKey === undefined) {\n throw new Error(\"Not an X25519 public key\");\n }\n return this._x25519PublicKey;\n }\n\n /**\n * Returns the MLKEM public key if this is an MLKEM encapsulation key.\n * @throws Error if this is not an MLKEM key\n */\n mlkemPublicKey(): MLKEMPublicKey {\n if (this._mlkemPublicKey === undefined) {\n throw new Error(\"Not an MLKEM public key\");\n }\n return this._mlkemPublicKey;\n }\n\n /**\n * Returns the X25519 public key if available, or null.\n */\n toX25519(): X25519PublicKey | null {\n return this._x25519PublicKey ?? null;\n }\n\n /**\n * Returns the MLKEM public key if available, or null.\n */\n toMlkem(): MLKEMPublicKey | null {\n return this._mlkemPublicKey ?? null;\n }\n\n /**\n * Returns the raw public key data.\n */\n data(): Uint8Array {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PublicKey;\n if (pk === undefined) throw new Error(\"X25519 public key not set\");\n return pk.data();\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPublicKey;\n if (pk === undefined) throw new Error(\"MLKEM public key not set\");\n return pk.data();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns this object as an EncapsulationPublicKey.\n *\n * This method allows EncapsulationPublicKey to implement the Encrypter interface.\n * Since this class is itself an encapsulation public key, it returns `this`.\n *\n * @returns This encapsulation public key\n */\n encapsulationPublicKey(): EncapsulationPublicKey {\n return this;\n }\n\n /**\n * Encapsulate a new shared secret for this public key.\n *\n * This generates a random shared secret and encapsulates it so that only\n * the holder of the corresponding private key can recover it.\n *\n * @returns A tuple of [sharedSecret, ciphertext]\n */\n encapsulateNewSharedSecret(): [SymmetricKey, EncapsulationCiphertext] {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PublicKey;\n if (pk === undefined) throw new Error(\"X25519 public key not set\");\n // Generate ephemeral key pair\n const [ephemeralPrivate, ephemeralPublic] = X25519PrivateKey.keypair();\n\n // Perform ECDH to get shared secret\n const sharedSecret = ephemeralPrivate.sharedKeyWith(pk);\n\n // The \"ciphertext\" is the ephemeral public key\n const ciphertext = EncapsulationCiphertext.fromX25519PublicKey(ephemeralPublic);\n\n return [sharedSecret, ciphertext];\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPublicKey;\n if (pk === undefined) throw new Error(\"MLKEM public key not set\");\n\n // Encapsulate using MLKEM\n const { sharedSecret, ciphertext: mlkemCiphertext } = pk.encapsulate();\n\n // Wrap in EncapsulationCiphertext\n const ciphertext = EncapsulationCiphertext.fromMlkem(mlkemCiphertext);\n\n return [sharedSecret, ciphertext];\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Compare with another EncapsulationPublicKey.\n */\n equals(other: EncapsulationPublicKey): boolean {\n if (this._scheme !== other._scheme) return false;\n if (this._scheme === EncapsulationScheme.X25519) {\n const thisPk = this._x25519PublicKey;\n const otherPk = other._x25519PublicKey;\n if (thisPk === undefined || otherPk === undefined) return false;\n return thisPk.equals(otherPk);\n } else if (isMlkemScheme(this._scheme)) {\n const thisPk = this._mlkemPublicKey;\n const otherPk = other._mlkemPublicKey;\n if (thisPk === undefined || otherPk === undefined) return false;\n return thisPk.equals(otherPk);\n }\n return false;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n if (this._scheme === EncapsulationScheme.X25519) {\n return `EncapsulationPublicKey(X25519, ${bytesToHex(this.data()).substring(0, 16)}...)`;\n } else if (isMlkemScheme(this._scheme)) {\n return `EncapsulationPublicKey(${String(this._scheme)}, ${bytesToHex(this.data()).substring(0, 16)}...)`;\n }\n return `EncapsulationPublicKey(${String(this._scheme)})`;\n }\n\n // ============================================================================\n // ReferenceProvider Interface\n // ============================================================================\n\n /**\n * Returns a unique reference to this EncapsulationPublicKey instance.\n *\n * The reference is derived from the SHA-256 hash of the tagged CBOR\n * representation, providing a unique, content-addressable identifier.\n */\n reference(): Reference {\n const digest = Digest.fromImage(this.taggedCborData());\n return Reference.from(digest);\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with this public key.\n */\n cborTags(): Tag[] {\n if (this._scheme === EncapsulationScheme.X25519) {\n return tagsForValues([TAG_X25519_PUBLIC_KEY.value]);\n } else if (isMlkemScheme(this._scheme)) {\n return tagsForValues([TAG_MLKEM_PUBLIC_KEY.value]);\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n */\n untaggedCbor(): Cbor {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PublicKey;\n if (pk === undefined) throw new Error(\"X25519 public key not set\");\n return toByteString(pk.data());\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPublicKey;\n if (pk === undefined) throw new Error(\"MLKEM public key not set\");\n return pk.untaggedCbor();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an EncapsulationPublicKey by decoding it from untagged CBOR.\n * Note: Without tags, we assume X25519 scheme.\n */\n fromUntaggedCbor(cborValue: Cbor): EncapsulationPublicKey {\n const data = expectBytes(cborValue);\n const publicKey = X25519PublicKey.fromDataRef(data);\n return EncapsulationPublicKey.fromX25519PublicKey(publicKey);\n }\n\n /**\n * Creates an EncapsulationPublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): EncapsulationPublicKey {\n const tag = tagValue(cborValue);\n\n if (tag === TAG_X25519_PUBLIC_KEY.value) {\n const content = extractTaggedContent(cborValue);\n const data = expectBytes(content);\n const publicKey = X25519PublicKey.fromDataRef(data);\n return EncapsulationPublicKey.fromX25519PublicKey(publicKey);\n }\n\n if (tag === TAG_MLKEM_PUBLIC_KEY.value) {\n const mlkemPublic = MLKEMPublicKey.fromTaggedCbor(cborValue);\n return EncapsulationPublicKey.fromMlkem(mlkemPublic);\n }\n\n throw new Error(`Unknown public key tag: ${tag}`);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): EncapsulationPublicKey {\n const dummy = EncapsulationPublicKey.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): EncapsulationPublicKey {\n const cborValue = decodeCbor(data);\n return EncapsulationPublicKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): EncapsulationPublicKey {\n const cborValue = decodeCbor(data);\n const dummy = EncapsulationPublicKey.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n if (this._scheme === EncapsulationScheme.X25519) {\n const name = TAG_X25519_PUBLIC_KEY.name;\n if (name === undefined) throw new Error(\"TAG_X25519_PUBLIC_KEY.name is undefined\");\n return UR.new(name, this.untaggedCbor());\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPublicKey;\n if (pk === undefined) throw new Error(\"MLKEM public key not set\");\n return pk.ur();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an EncapsulationPublicKey from a UR.\n */\n static fromUR(ur: UR): EncapsulationPublicKey {\n // Check for known UR types\n if (ur.urTypeStr() === TAG_X25519_PUBLIC_KEY.name) {\n const dummy = EncapsulationPublicKey.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n if (ur.urTypeStr() === TAG_MLKEM_PUBLIC_KEY.name) {\n const mlkemPublic = MLKEMPublicKey.fromUR(ur);\n return EncapsulationPublicKey.fromMlkem(mlkemPublic);\n }\n\n throw new Error(`Unknown UR type for EncapsulationPublicKey: ${ur.urTypeStr()}`);\n }\n\n /**\n * Creates an EncapsulationPublicKey from a UR string.\n */\n static fromURString(urString: string): EncapsulationPublicKey {\n const ur = UR.fromURString(urString);\n return EncapsulationPublicKey.fromUR(ur);\n }\n}\n","/**\n * MLKEMPrivateKey - ML-KEM Private Key for post-quantum key decapsulation\n *\n * MLKEMPrivateKey wraps an ML-KEM secret key for decapsulating shared secrets.\n * It supports all three security levels (MLKEM512, MLKEM768, MLKEM1024).\n *\n * # CBOR Serialization\n *\n * MLKEMPrivateKey is serialized with tag 40100:\n * ```\n * #6.40100([level, h'<private-key-bytes>'])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `mlkem-private-key`\n *\n * Ported from bc-components-rust/src/mlkem/mlkem_private_key.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n expectInteger,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { MLKEM_PRIVATE_KEY as TAG_MLKEM_PRIVATE_KEY } from \"@bcts/tags\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\n\nimport {\n MLKEMLevel,\n mlkemLevelFromValue,\n mlkemLevelToString,\n mlkemPrivateKeySize,\n mlkemGenerateKeypairUsing,\n mlkemDecapsulate,\n mlkemExtractPublicKey,\n} from \"./mlkem-level.js\";\nimport { MLKEMPublicKey } from \"./mlkem-public-key.js\";\nimport type { MLKEMCiphertext } from \"./mlkem-ciphertext.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * MLKEMPrivateKey - Post-quantum key decapsulation private key using ML-KEM.\n */\nexport class MLKEMPrivateKey\n implements CborTaggedEncodable, CborTaggedDecodable<MLKEMPrivateKey>, UREncodable\n{\n private readonly _level: MLKEMLevel;\n private readonly _data: Uint8Array;\n\n private constructor(level: MLKEMLevel, data: Uint8Array) {\n const expectedSize = mlkemPrivateKeySize(level);\n if (data.length !== expectedSize) {\n throw new Error(\n `MLKEMPrivateKey (${mlkemLevelToString(level)}) must be ${expectedSize} bytes, got ${data.length}`,\n );\n }\n this._level = level;\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Generate a new random MLKEMPrivateKey with the specified security level.\n *\n * @param level - The ML-KEM security level (default: MLKEM768)\n */\n static new(level: MLKEMLevel = MLKEMLevel.MLKEM768): MLKEMPrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return MLKEMPrivateKey.newUsing(level, rng);\n }\n\n /**\n * Generate a new random MLKEMPrivateKey using the provided RNG.\n *\n * @param level - The ML-KEM security level\n * @param rng - Random number generator\n */\n static newUsing(level: MLKEMLevel, rng: RandomNumberGenerator): MLKEMPrivateKey {\n const keypair = mlkemGenerateKeypairUsing(level, rng);\n return new MLKEMPrivateKey(level, keypair.secretKey);\n }\n\n /**\n * Create an MLKEMPrivateKey from raw bytes.\n *\n * @param level - The ML-KEM security level\n * @param data - The private key bytes\n */\n static fromBytes(level: MLKEMLevel, data: Uint8Array): MLKEMPrivateKey {\n return new MLKEMPrivateKey(level, data);\n }\n\n /**\n * Generate a keypair and return both private and public keys.\n *\n * @param level - The ML-KEM security level (default: MLKEM768)\n * @returns Tuple of [privateKey, publicKey]\n */\n static keypair(level: MLKEMLevel = MLKEMLevel.MLKEM768): [MLKEMPrivateKey, MLKEMPublicKey] {\n const rng = new SecureRandomNumberGenerator();\n return MLKEMPrivateKey.keypairUsing(level, rng);\n }\n\n /**\n * Generate a keypair using the provided RNG.\n *\n * @param level - The ML-KEM security level\n * @param rng - Random number generator\n * @returns Tuple of [privateKey, publicKey]\n */\n static keypairUsing(\n level: MLKEMLevel,\n rng: RandomNumberGenerator,\n ): [MLKEMPrivateKey, MLKEMPublicKey] {\n const keypairData = mlkemGenerateKeypairUsing(level, rng);\n const privateKey = new MLKEMPrivateKey(level, keypairData.secretKey);\n const publicKey = MLKEMPublicKey.fromBytes(level, keypairData.publicKey);\n return [privateKey, publicKey];\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the security level of this key.\n */\n level(): MLKEMLevel {\n return this._level;\n }\n\n /**\n * Returns the raw key bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw key bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the size of the key in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n /**\n * Decapsulate a shared secret from a ciphertext.\n *\n * @param ciphertext - The ML-KEM ciphertext\n * @returns The decapsulated shared secret as a SymmetricKey\n */\n decapsulate(ciphertext: MLKEMCiphertext): SymmetricKey {\n if (ciphertext.level() !== this._level) {\n throw new Error(\n `Ciphertext level (${mlkemLevelToString(ciphertext.level())}) does not match key level (${mlkemLevelToString(this._level)})`,\n );\n }\n const sharedSecret = mlkemDecapsulate(this._level, this._data, ciphertext.asBytes());\n return SymmetricKey.fromData(sharedSecret);\n }\n\n /**\n * Derives and returns the corresponding public key.\n *\n * In ML-KEM (FIPS 203), the decapsulation key contains the encapsulation key (public key)\n * embedded within it. This method extracts that public key.\n *\n * @returns The corresponding MLKEMPublicKey\n */\n publicKey(): MLKEMPublicKey {\n const publicKeyData = mlkemExtractPublicKey(this._level, this._data);\n return MLKEMPublicKey.fromBytes(this._level, publicKeyData);\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another MLKEMPrivateKey.\n */\n equals(other: MLKEMPrivateKey): boolean {\n if (this._level !== other._level) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation (truncated for security).\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `MLKEMPrivateKey(${mlkemLevelToString(this._level)}, ${hex.substring(0, 8)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with MLKEMPrivateKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_MLKEM_PRIVATE_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [level, key_bytes]\n */\n untaggedCbor(): Cbor {\n return cbor([this._level, this._data]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an MLKEMPrivateKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): MLKEMPrivateKey {\n const elements = expectArray(cborValue);\n if (elements.length !== 2) {\n throw new Error(`MLKEMPrivateKey CBOR must have 2 elements, got ${elements.length}`);\n }\n const levelValue = Number(expectInteger(elements[0]));\n const level = mlkemLevelFromValue(levelValue);\n const data = expectBytes(elements[1]);\n return MLKEMPrivateKey.fromBytes(level, data);\n }\n\n /**\n * Creates an MLKEMPrivateKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): MLKEMPrivateKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): MLKEMPrivateKey {\n // Create a minimal dummy instance for decoding\n const dummyData = new Uint8Array(mlkemPrivateKeySize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMPrivateKey(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): MLKEMPrivateKey {\n const cborValue = decodeCbor(data);\n return MLKEMPrivateKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): MLKEMPrivateKey {\n const cborValue = decodeCbor(data);\n const dummyData = new Uint8Array(mlkemPrivateKeySize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMPrivateKey(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_MLKEM_PRIVATE_KEY.name;\n if (name === undefined) {\n throw new Error(\"MLKEM_PRIVATE_KEY tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an MLKEMPrivateKey from a UR.\n */\n static fromUR(ur: UR): MLKEMPrivateKey {\n if (ur.urTypeStr() !== TAG_MLKEM_PRIVATE_KEY.name) {\n throw new Error(`Expected UR type ${TAG_MLKEM_PRIVATE_KEY.name}, got ${ur.urTypeStr()}`);\n }\n const dummyData = new Uint8Array(mlkemPrivateKeySize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMPrivateKey(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an MLKEMPrivateKey from a UR string.\n */\n static fromURString(urString: string): MLKEMPrivateKey {\n const ur = UR.fromURString(urString);\n return MLKEMPrivateKey.fromUR(ur);\n }\n}\n","/**\n * Encapsulation private key for key encapsulation mechanisms\n *\n * This type represents a private key that can be used to decapsulate (decrypt)\n * a shared secret that was encapsulated using the corresponding public key.\n *\n * For X25519, decapsulation works by:\n * 1. Receiving the ephemeral public key (ciphertext)\n * 2. Performing ECDH with the private key and the ephemeral public key\n * 3. Returning the shared secret\n *\n * For MLKEM, decapsulation uses the ML-KEM algorithm to recover the shared secret.\n *\n * # CBOR Serialization\n *\n * For X25519, the private key is serialized with tag 40010.\n * For MLKEM, the private key is serialized with tag 40100.\n *\n * Ported from bc-components-rust/src/encapsulation/encapsulation_private_key.rs\n */\n\nimport { SecureRandomNumberGenerator, type RandomNumberGenerator } from \"@bcts/rand\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n tagValue,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport {\n X25519_PRIVATE_KEY as TAG_X25519_PRIVATE_KEY,\n MLKEM_PRIVATE_KEY as TAG_MLKEM_PRIVATE_KEY,\n} from \"@bcts/tags\";\nimport { X25519PrivateKey } from \"../x25519/x25519-private-key.js\";\nimport { type SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { EncapsulationScheme } from \"./encapsulation-scheme.js\";\nimport { type EncapsulationCiphertext } from \"./encapsulation-ciphertext.js\";\nimport { EncapsulationPublicKey } from \"./encapsulation-public-key.js\";\nimport { MLKEMPrivateKey } from \"../mlkem/mlkem-private-key.js\";\nimport { MLKEMLevel } from \"../mlkem/mlkem-level.js\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex } from \"../utils.js\";\nimport { Reference, type ReferenceProvider } from \"../reference.js\";\nimport { Digest } from \"../digest.js\";\n\n/**\n * Convert MLKEMLevel to EncapsulationScheme\n */\nfunction mlkemLevelToScheme(level: MLKEMLevel): EncapsulationScheme {\n switch (level) {\n case MLKEMLevel.MLKEM512:\n return EncapsulationScheme.MLKEM512;\n case MLKEMLevel.MLKEM768:\n return EncapsulationScheme.MLKEM768;\n case MLKEMLevel.MLKEM1024:\n return EncapsulationScheme.MLKEM1024;\n }\n}\n\n/**\n * Check if a scheme is an MLKEM scheme\n */\nfunction isMlkemScheme(scheme: EncapsulationScheme): boolean {\n return (\n scheme === EncapsulationScheme.MLKEM512 ||\n scheme === EncapsulationScheme.MLKEM768 ||\n scheme === EncapsulationScheme.MLKEM1024\n );\n}\n\n/**\n * Represents a private key for key encapsulation.\n *\n * Use this to decapsulate a shared secret from ciphertext.\n */\nexport class EncapsulationPrivateKey\n implements\n ReferenceProvider,\n CborTaggedEncodable,\n CborTaggedDecodable<EncapsulationPrivateKey>,\n UREncodable\n{\n private readonly _scheme: EncapsulationScheme;\n private readonly _x25519PrivateKey: X25519PrivateKey | undefined;\n private readonly _mlkemPrivateKey: MLKEMPrivateKey | undefined;\n\n private constructor(\n scheme: EncapsulationScheme,\n x25519PrivateKey?: X25519PrivateKey,\n mlkemPrivateKey?: MLKEMPrivateKey,\n ) {\n this._scheme = scheme;\n this._x25519PrivateKey = x25519PrivateKey;\n this._mlkemPrivateKey = mlkemPrivateKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an EncapsulationPrivateKey from an X25519PrivateKey.\n */\n static fromX25519PrivateKey(privateKey: X25519PrivateKey): EncapsulationPrivateKey {\n return new EncapsulationPrivateKey(EncapsulationScheme.X25519, privateKey, undefined);\n }\n\n /**\n * Create an EncapsulationPrivateKey from raw X25519 private key bytes.\n */\n static fromX25519Data(data: Uint8Array): EncapsulationPrivateKey {\n const privateKey = X25519PrivateKey.fromDataRef(data);\n return EncapsulationPrivateKey.fromX25519PrivateKey(privateKey);\n }\n\n /**\n * Create an EncapsulationPrivateKey from an MLKEMPrivateKey.\n */\n static fromMlkem(privateKey: MLKEMPrivateKey): EncapsulationPrivateKey {\n const scheme = mlkemLevelToScheme(privateKey.level());\n return new EncapsulationPrivateKey(scheme, undefined, privateKey);\n }\n\n /**\n * Create an EncapsulationPrivateKey from raw MLKEM private key bytes.\n */\n static fromMlkemData(level: MLKEMLevel, data: Uint8Array): EncapsulationPrivateKey {\n const privateKey = MLKEMPrivateKey.fromBytes(level, data);\n return EncapsulationPrivateKey.fromMlkem(privateKey);\n }\n\n /**\n * Generate a new random X25519 encapsulation private key.\n */\n static new(): EncapsulationPrivateKey {\n return EncapsulationPrivateKey.random();\n }\n\n /**\n * Generate a new random X25519 encapsulation private key.\n */\n static random(): EncapsulationPrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return EncapsulationPrivateKey.newUsing(rng);\n }\n\n /**\n * Generate a new random X25519 encapsulation private key using provided RNG.\n */\n static newUsing(rng: RandomNumberGenerator): EncapsulationPrivateKey {\n const x25519Private = X25519PrivateKey.newUsing(rng);\n return EncapsulationPrivateKey.fromX25519PrivateKey(x25519Private);\n }\n\n /**\n * Generate a new MLKEM encapsulation private key.\n */\n static newMlkem(level: MLKEMLevel = MLKEMLevel.MLKEM768): EncapsulationPrivateKey {\n const mlkemPrivate = MLKEMPrivateKey.new(level);\n return EncapsulationPrivateKey.fromMlkem(mlkemPrivate);\n }\n\n /**\n * Generate a new MLKEM encapsulation private key using provided RNG.\n */\n static newMlkemUsing(level: MLKEMLevel, rng: RandomNumberGenerator): EncapsulationPrivateKey {\n const mlkemPrivate = MLKEMPrivateKey.newUsing(level, rng);\n return EncapsulationPrivateKey.fromMlkem(mlkemPrivate);\n }\n\n /**\n * Generate a new keypair for X25519.\n */\n static keypair(): [EncapsulationPrivateKey, EncapsulationPublicKey] {\n const privateKey = EncapsulationPrivateKey.new();\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Generate a new keypair using the given RNG (X25519).\n */\n static keypairUsing(\n rng: RandomNumberGenerator,\n ): [EncapsulationPrivateKey, EncapsulationPublicKey] {\n const privateKey = EncapsulationPrivateKey.newUsing(rng);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Generate a new MLKEM keypair.\n */\n static mlkemKeypair(\n level: MLKEMLevel = MLKEMLevel.MLKEM768,\n ): [EncapsulationPrivateKey, EncapsulationPublicKey] {\n const [mlkemPrivate, mlkemPublic] = MLKEMPrivateKey.keypair(level);\n const privateKey = EncapsulationPrivateKey.fromMlkem(mlkemPrivate);\n const publicKey = EncapsulationPublicKey.fromMlkem(mlkemPublic);\n return [privateKey, publicKey];\n }\n\n /**\n * Generate a new MLKEM keypair using the given RNG.\n */\n static mlkemKeypairUsing(\n level: MLKEMLevel,\n rng: RandomNumberGenerator,\n ): [EncapsulationPrivateKey, EncapsulationPublicKey] {\n const [mlkemPrivate, mlkemPublic] = MLKEMPrivateKey.keypairUsing(level, rng);\n const privateKey = EncapsulationPrivateKey.fromMlkem(mlkemPrivate);\n const publicKey = EncapsulationPublicKey.fromMlkem(mlkemPublic);\n return [privateKey, publicKey];\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the encapsulation scheme.\n */\n encapsulationScheme(): EncapsulationScheme {\n return this._scheme;\n }\n\n /**\n * Returns true if this is an X25519 private key.\n */\n isX25519(): boolean {\n return this._scheme === EncapsulationScheme.X25519;\n }\n\n /**\n * Returns true if this is an MLKEM private key.\n */\n isMlkem(): boolean {\n return isMlkemScheme(this._scheme);\n }\n\n /**\n * Returns the X25519 private key if this is an X25519 encapsulation key.\n * @throws Error if this is not an X25519 key\n */\n x25519PrivateKey(): X25519PrivateKey {\n if (this._x25519PrivateKey === undefined) {\n throw new Error(\"Not an X25519 private key\");\n }\n return this._x25519PrivateKey;\n }\n\n /**\n * Returns the MLKEM private key if this is an MLKEM encapsulation key.\n * @throws Error if this is not an MLKEM key\n */\n mlkemPrivateKey(): MLKEMPrivateKey {\n if (this._mlkemPrivateKey === undefined) {\n throw new Error(\"Not an MLKEM private key\");\n }\n return this._mlkemPrivateKey;\n }\n\n /**\n * Returns the X25519 private key if available, or null.\n */\n toX25519(): X25519PrivateKey | null {\n return this._x25519PrivateKey ?? null;\n }\n\n /**\n * Returns the MLKEM private key if available, or null.\n */\n toMlkem(): MLKEMPrivateKey | null {\n return this._mlkemPrivateKey ?? null;\n }\n\n /**\n * Returns the raw private key data.\n */\n data(): Uint8Array {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PrivateKey;\n if (pk === undefined) throw new Error(\"X25519 private key not set\");\n return pk.data();\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPrivateKey;\n if (pk === undefined) throw new Error(\"MLKEM private key not set\");\n return pk.data();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Get the public key corresponding to this private key.\n */\n publicKey(): EncapsulationPublicKey {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PrivateKey;\n if (pk === undefined) throw new Error(\"X25519 private key not set\");\n const x25519Public = pk.publicKey();\n return EncapsulationPublicKey.fromX25519PublicKey(x25519Public);\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPrivateKey;\n if (pk === undefined) throw new Error(\"MLKEM private key not set\");\n const mlkemPublic = pk.publicKey();\n return EncapsulationPublicKey.fromMlkem(mlkemPublic);\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Decapsulate a shared secret from ciphertext.\n *\n * @param ciphertext - The ciphertext from encapsulation\n * @returns The decapsulated shared secret\n * @throws CryptoError if the scheme doesn't match\n */\n decapsulateSharedSecret(ciphertext: EncapsulationCiphertext): SymmetricKey {\n // Verify scheme matches\n if (ciphertext.encapsulationScheme() !== this._scheme) {\n throw CryptoError.invalidData(\n `Scheme mismatch: expected ${String(this._scheme)}, got ${String(ciphertext.encapsulationScheme())}`,\n );\n }\n\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PrivateKey;\n if (pk === undefined) throw new Error(\"X25519 private key not set\");\n // Get the ephemeral public key from ciphertext\n const ephemeralPublic = ciphertext.x25519PublicKey();\n\n // Perform ECDH to recover shared secret\n return pk.sharedKeyWith(ephemeralPublic);\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPrivateKey;\n if (pk === undefined) throw new Error(\"MLKEM private key not set\");\n // Get the MLKEM ciphertext and decapsulate\n const mlkemCiphertext = ciphertext.mlkemCiphertext();\n return pk.decapsulate(mlkemCiphertext);\n }\n\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Compare with another EncapsulationPrivateKey.\n */\n equals(other: EncapsulationPrivateKey): boolean {\n if (this._scheme !== other._scheme) return false;\n if (this._scheme === EncapsulationScheme.X25519) {\n const thisPk = this._x25519PrivateKey;\n const otherPk = other._x25519PrivateKey;\n if (thisPk === undefined || otherPk === undefined) return false;\n return thisPk.equals(otherPk);\n } else if (isMlkemScheme(this._scheme)) {\n const thisPk = this._mlkemPrivateKey;\n const otherPk = other._mlkemPrivateKey;\n if (thisPk === undefined || otherPk === undefined) return false;\n return thisPk.equals(otherPk);\n }\n return false;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n if (this._scheme === EncapsulationScheme.X25519) {\n return `EncapsulationPrivateKey(X25519, ${bytesToHex(this.data()).substring(0, 16)}...)`;\n } else if (isMlkemScheme(this._scheme)) {\n return `EncapsulationPrivateKey(${String(this._scheme)}, ${bytesToHex(this.data()).substring(0, 16)}...)`;\n }\n return `EncapsulationPrivateKey(${String(this._scheme)})`;\n }\n\n // ============================================================================\n // ReferenceProvider Interface\n // ============================================================================\n\n /**\n * Returns a unique reference to this EncapsulationPrivateKey instance.\n *\n * The reference is derived from the SHA-256 hash of the tagged CBOR\n * representation, providing a unique, content-addressable identifier.\n */\n reference(): Reference {\n const digest = Digest.fromImage(this.taggedCborData());\n return Reference.from(digest);\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with this private key.\n */\n cborTags(): Tag[] {\n if (this._scheme === EncapsulationScheme.X25519) {\n return tagsForValues([TAG_X25519_PRIVATE_KEY.value]);\n } else if (isMlkemScheme(this._scheme)) {\n return tagsForValues([TAG_MLKEM_PRIVATE_KEY.value]);\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n */\n untaggedCbor(): Cbor {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PrivateKey;\n if (pk === undefined) throw new Error(\"X25519 private key not set\");\n return toByteString(pk.data());\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPrivateKey;\n if (pk === undefined) throw new Error(\"MLKEM private key not set\");\n return pk.untaggedCbor();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an EncapsulationPrivateKey by decoding it from untagged CBOR.\n * Note: Without tags, we assume X25519 scheme.\n */\n fromUntaggedCbor(cborValue: Cbor): EncapsulationPrivateKey {\n const data = expectBytes(cborValue);\n const privateKey = X25519PrivateKey.fromDataRef(data);\n return EncapsulationPrivateKey.fromX25519PrivateKey(privateKey);\n }\n\n /**\n * Creates an EncapsulationPrivateKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): EncapsulationPrivateKey {\n const tag = tagValue(cborValue);\n\n if (tag === TAG_X25519_PRIVATE_KEY.value) {\n const content = extractTaggedContent(cborValue);\n const data = expectBytes(content);\n const privateKey = X25519PrivateKey.fromDataRef(data);\n return EncapsulationPrivateKey.fromX25519PrivateKey(privateKey);\n }\n\n if (tag === TAG_MLKEM_PRIVATE_KEY.value) {\n const mlkemPrivate = MLKEMPrivateKey.fromTaggedCbor(cborValue);\n return EncapsulationPrivateKey.fromMlkem(mlkemPrivate);\n }\n\n throw new Error(`Unknown private key tag: ${tag}`);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): EncapsulationPrivateKey {\n const dummy = EncapsulationPrivateKey.fromX25519PrivateKey(\n X25519PrivateKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): EncapsulationPrivateKey {\n const cborValue = decodeCbor(data);\n return EncapsulationPrivateKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): EncapsulationPrivateKey {\n const cborValue = decodeCbor(data);\n const dummy = EncapsulationPrivateKey.fromX25519PrivateKey(\n X25519PrivateKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n if (this._scheme === EncapsulationScheme.X25519) {\n const name = TAG_X25519_PRIVATE_KEY.name;\n if (name === undefined) throw new Error(\"TAG_X25519_PRIVATE_KEY.name is undefined\");\n return UR.new(name, this.untaggedCbor());\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPrivateKey;\n if (pk === undefined) throw new Error(\"MLKEM private key not set\");\n return pk.ur();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an EncapsulationPrivateKey from a UR.\n */\n static fromUR(ur: UR): EncapsulationPrivateKey {\n // Check for known UR types\n if (ur.urTypeStr() === TAG_X25519_PRIVATE_KEY.name) {\n const dummy = EncapsulationPrivateKey.fromX25519PrivateKey(\n X25519PrivateKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n if (ur.urTypeStr() === TAG_MLKEM_PRIVATE_KEY.name) {\n const mlkemPrivate = MLKEMPrivateKey.fromUR(ur);\n return EncapsulationPrivateKey.fromMlkem(mlkemPrivate);\n }\n\n throw new Error(`Unknown UR type for EncapsulationPrivateKey: ${ur.urTypeStr()}`);\n }\n\n /**\n * Creates an EncapsulationPrivateKey from a UR string.\n */\n static fromURString(urString: string): EncapsulationPrivateKey {\n const ur = UR.fromURString(urString);\n return EncapsulationPrivateKey.fromUR(ur);\n }\n}\n","/**\n * Encapsulation scheme enum for key encapsulation mechanisms\n *\n * This enum represents the available key encapsulation mechanisms (KEMs)\n * for establishing shared secrets between parties.\n *\n * Supported schemes:\n * - X25519: Curve25519-based Diffie-Hellman key exchange (default)\n * - MLKEM512, MLKEM768, MLKEM1024: ML-KEM at various security levels\n *\n * Ported from bc-components-rust/src/encapsulation/encapsulation_scheme.rs\n */\n\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { EncapsulationPrivateKey } from \"./encapsulation-private-key.js\";\nimport type { EncapsulationPublicKey } from \"./encapsulation-public-key.js\";\nimport { MLKEMLevel } from \"../mlkem/mlkem-level.js\";\n\n/**\n * Available key encapsulation schemes.\n */\nexport enum EncapsulationScheme {\n /**\n * X25519 Diffie-Hellman key exchange (default).\n * Based on Curve25519 as defined in RFC 7748.\n */\n X25519 = \"x25519\",\n\n /**\n * ML-KEM-512 post-quantum key encapsulation (NIST security level 1).\n */\n MLKEM512 = \"mlkem512\",\n\n /**\n * ML-KEM-768 post-quantum key encapsulation (NIST security level 3).\n */\n MLKEM768 = \"mlkem768\",\n\n /**\n * ML-KEM-1024 post-quantum key encapsulation (NIST security level 5).\n */\n MLKEM1024 = \"mlkem1024\",\n}\n\n/**\n * Returns the default encapsulation scheme (X25519).\n */\nexport function defaultEncapsulationScheme(): EncapsulationScheme {\n return EncapsulationScheme.X25519;\n}\n\n/**\n * Check if a scheme is an MLKEM scheme.\n */\nexport function isMlkemScheme(scheme: EncapsulationScheme): boolean {\n return (\n scheme === EncapsulationScheme.MLKEM512 ||\n scheme === EncapsulationScheme.MLKEM768 ||\n scheme === EncapsulationScheme.MLKEM1024\n );\n}\n\n/**\n * Convert EncapsulationScheme to MLKEMLevel.\n * @throws Error if scheme is not an MLKEM scheme\n */\nexport function schemeToMlkemLevel(scheme: EncapsulationScheme): MLKEMLevel {\n switch (scheme) {\n case EncapsulationScheme.X25519:\n throw new Error(`Not an MLKEM scheme: ${String(scheme)}`);\n case EncapsulationScheme.MLKEM512:\n return MLKEMLevel.MLKEM512;\n case EncapsulationScheme.MLKEM768:\n return MLKEMLevel.MLKEM768;\n case EncapsulationScheme.MLKEM1024:\n return MLKEMLevel.MLKEM1024;\n }\n}\n\n/**\n * Convert MLKEMLevel to EncapsulationScheme.\n */\nexport function mlkemLevelToScheme(level: MLKEMLevel): EncapsulationScheme {\n switch (level) {\n case MLKEMLevel.MLKEM512:\n return EncapsulationScheme.MLKEM512;\n case MLKEMLevel.MLKEM768:\n return EncapsulationScheme.MLKEM768;\n case MLKEMLevel.MLKEM1024:\n return EncapsulationScheme.MLKEM1024;\n }\n}\n\n/**\n * Generate a new keypair for the given encapsulation scheme.\n *\n * @param scheme - The encapsulation scheme to use (defaults to X25519)\n * @returns A tuple of [privateKey, publicKey]\n */\nexport function createEncapsulationKeypair(\n scheme: EncapsulationScheme = EncapsulationScheme.X25519,\n): [EncapsulationPrivateKey, EncapsulationPublicKey] {\n switch (scheme) {\n case EncapsulationScheme.X25519:\n return EncapsulationPrivateKey.keypair();\n case EncapsulationScheme.MLKEM512:\n return EncapsulationPrivateKey.mlkemKeypair(MLKEMLevel.MLKEM512);\n case EncapsulationScheme.MLKEM768:\n return EncapsulationPrivateKey.mlkemKeypair(MLKEMLevel.MLKEM768);\n case EncapsulationScheme.MLKEM1024:\n return EncapsulationPrivateKey.mlkemKeypair(MLKEMLevel.MLKEM1024);\n }\n}\n\n/**\n * Generate a new keypair for the given encapsulation scheme using a specific RNG.\n *\n * Note: Only X25519 supports deterministic keypair generation.\n * MLKEM schemes do not support deterministic generation (matching Rust behavior).\n *\n * @param rng - The random number generator to use\n * @param scheme - The encapsulation scheme to use (defaults to X25519)\n * @returns A tuple of [privateKey, publicKey]\n * @throws Error if the scheme doesn't support deterministic generation\n */\nexport function createEncapsulationKeypairUsing(\n rng: RandomNumberGenerator,\n scheme: EncapsulationScheme = EncapsulationScheme.X25519,\n): [EncapsulationPrivateKey, EncapsulationPublicKey] {\n switch (scheme) {\n case EncapsulationScheme.X25519:\n return EncapsulationPrivateKey.keypairUsing(rng);\n case EncapsulationScheme.MLKEM512:\n case EncapsulationScheme.MLKEM768:\n case EncapsulationScheme.MLKEM1024:\n // MLKEM doesn't support deterministic keypair generation (matching Rust behavior)\n throw new Error(\n \"Deterministic keypair generation not supported for this encapsulation scheme\",\n );\n }\n}\n","/**\n * Sealed message for anonymous authenticated encryption\n *\n * A `SealedMessage` combines key encapsulation with symmetric encryption to\n * provide anonymous authenticated encryption. The sender's identity is not\n * revealed, and only the intended recipient can decrypt the message.\n *\n * The sealing process:\n * 1. Encapsulate a new shared secret using the recipient's public key\n * 2. Use the shared secret to encrypt the plaintext with ChaCha20-Poly1305\n * 3. Return the encrypted message and the encapsulation ciphertext\n *\n * The unsealing process:\n * 1. Decapsulate the shared secret using the recipient's private key\n * 2. Use the shared secret to decrypt the ciphertext\n * 3. Return the plaintext\n *\n * Features:\n * - Anonymous sender (sender identity not revealed)\n * - Authenticated encryption\n * - Forward secrecy (each message uses different ephemeral key)\n *\n * # CBOR Serialization\n *\n * `SealedMessage` is serialized as a 2-element array with tag 40019:\n *\n * ```cddl\n * SealedMessage = #6.40019([\n * message: EncryptedMessage,\n * encapsulated_key: EncapsulationCiphertext\n * ])\n * ```\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `SealedMessage` is\n * represented with the type \"crypto-sealed\".\n *\n * Ported from bc-components-rust/src/encapsulation/sealed_message.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { SEALED_MESSAGE as TAG_SEALED_MESSAGE } from \"@bcts/tags\";\nimport { Nonce } from \"../nonce.js\";\nimport { EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { type EncapsulationScheme } from \"./encapsulation-scheme.js\";\nimport { EncapsulationCiphertext } from \"./encapsulation-ciphertext.js\";\nimport { type EncapsulationPublicKey } from \"./encapsulation-public-key.js\";\nimport { type EncapsulationPrivateKey } from \"./encapsulation-private-key.js\";\nimport { X25519PublicKey } from \"../x25519/x25519-public-key.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * A sealed message providing anonymous authenticated encryption.\n */\nexport class SealedMessage\n implements CborTaggedEncodable, CborTaggedDecodable<SealedMessage>, UREncodable\n{\n private readonly _message: EncryptedMessage;\n private readonly _encapsulatedKey: EncapsulationCiphertext;\n\n private constructor(message: EncryptedMessage, encapsulatedKey: EncapsulationCiphertext) {\n this._message = message;\n this._encapsulatedKey = encapsulatedKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a SealedMessage from its components.\n */\n static from(message: EncryptedMessage, encapsulatedKey: EncapsulationCiphertext): SealedMessage {\n return new SealedMessage(message, encapsulatedKey);\n }\n\n /**\n * Seal a message for a recipient (no additional authenticated data).\n *\n * @param plaintext - The message to encrypt\n * @param recipient - The recipient's public key\n * @returns A sealed message that only the recipient can decrypt\n */\n static new(plaintext: Uint8Array, recipient: EncapsulationPublicKey): SealedMessage {\n return SealedMessage.newWithAad(plaintext, recipient, new Uint8Array(0));\n }\n\n /**\n * Seal a message for a recipient with additional authenticated data.\n *\n * @param plaintext - The message to encrypt\n * @param recipient - The recipient's public key\n * @param aad - Additional authenticated data (not encrypted but authenticated)\n * @returns A sealed message that only the recipient can decrypt\n */\n static newWithAad(\n plaintext: Uint8Array,\n recipient: EncapsulationPublicKey,\n aad: Uint8Array,\n ): SealedMessage {\n return SealedMessage.newOpt(plaintext, recipient, aad, undefined);\n }\n\n /**\n * Seal a message with optional test nonce (for deterministic testing).\n *\n * @param plaintext - The message to encrypt\n * @param recipient - The recipient's public key\n * @param aad - Additional authenticated data\n * @param testNonce - Optional fixed nonce for testing (DO NOT use in production)\n * @returns A sealed message\n */\n static newOpt(\n plaintext: Uint8Array,\n recipient: EncapsulationPublicKey,\n aad: Uint8Array,\n testNonce?: Nonce,\n ): SealedMessage {\n // Encapsulate a new shared secret\n const [sharedSecret, ciphertext] = recipient.encapsulateNewSharedSecret();\n\n // Use the nonce or generate a random one\n const nonce = testNonce ?? Nonce.new();\n\n // Encrypt the plaintext using the shared secret\n const encryptedMessage = sharedSecret.encrypt(plaintext, aad, nonce);\n\n return new SealedMessage(encryptedMessage, ciphertext);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the encrypted message.\n */\n message(): EncryptedMessage {\n return this._message;\n }\n\n /**\n * Returns the encapsulation ciphertext (ephemeral public key for X25519).\n */\n encapsulatedKey(): EncapsulationCiphertext {\n return this._encapsulatedKey;\n }\n\n /**\n * Returns the encapsulation scheme used.\n */\n encapsulationScheme(): EncapsulationScheme {\n return this._encapsulatedKey.encapsulationScheme();\n }\n\n /**\n * Decrypt the sealed message using the recipient's private key.\n *\n * @param privateKey - The recipient's private key\n * @returns The decrypted plaintext\n * @throws Error if decryption fails\n */\n decrypt(privateKey: EncapsulationPrivateKey): Uint8Array {\n // Decapsulate the shared secret\n const sharedSecret = privateKey.decapsulateSharedSecret(this._encapsulatedKey);\n\n // Decrypt the message\n return sharedSecret.decrypt(this._message);\n }\n\n /**\n * Compare with another SealedMessage.\n */\n equals(other: SealedMessage): boolean {\n return (\n this._message.equals(other._message) && this._encapsulatedKey.equals(other._encapsulatedKey)\n );\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `SealedMessage(${this._encapsulatedKey.encapsulationScheme()}, ciphertext: ${bytesToHex(this._message.ciphertext()).substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with SealedMessage.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SEALED_MESSAGE.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n * Format: [EncryptedMessage (tagged), EncapsulationCiphertext (tagged)]\n */\n untaggedCbor(): Cbor {\n const elements: Cbor[] = [this._message.taggedCbor(), this._encapsulatedKey.taggedCbor()];\n return cbor(elements);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a SealedMessage by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): SealedMessage {\n const elements = expectArray(cborValue);\n\n if (elements.length !== 2) {\n throw new Error(`SealedMessage must have 2 elements, got ${elements.length}`);\n }\n\n // Decode the encrypted message (tagged)\n const message = EncryptedMessage.fromTaggedCbor(elements[0]);\n\n // Decode the encapsulation ciphertext (tagged)\n const encapsulatedKey = EncapsulationCiphertext.fromTaggedCbor(elements[1]);\n\n return new SealedMessage(message, encapsulatedKey);\n }\n\n /**\n * Creates a SealedMessage by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): SealedMessage {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): SealedMessage {\n const dummyMessage = EncryptedMessage.new(\n new Uint8Array(0),\n new Uint8Array(0),\n Nonce.new(),\n new Uint8Array(16),\n );\n const dummyCiphertext = EncapsulationCiphertext.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n const dummy = new SealedMessage(dummyMessage, dummyCiphertext);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): SealedMessage {\n const cborValue = decodeCbor(data);\n return SealedMessage.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): SealedMessage {\n const cborValue = decodeCbor(data);\n const dummyMessage = EncryptedMessage.new(\n new Uint8Array(0),\n new Uint8Array(0),\n Nonce.new(),\n new Uint8Array(16),\n );\n const dummyCiphertext = EncapsulationCiphertext.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n const dummy = new SealedMessage(dummyMessage, dummyCiphertext);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the SealedMessage.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n const name = TAG_SEALED_MESSAGE.name;\n if (name === undefined) {\n throw new Error(\"TAG_SEALED_MESSAGE.name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a SealedMessage from a UR.\n */\n static fromUR(ur: UR): SealedMessage {\n const name = TAG_SEALED_MESSAGE.name;\n if (name === undefined) {\n throw new Error(\"TAG_SEALED_MESSAGE.name is undefined\");\n }\n ur.checkType(name);\n return SealedMessage.fromUntaggedCborData(ur.cbor().toData());\n }\n\n /**\n * Creates a SealedMessage from a UR string.\n */\n static fromURString(urString: string): SealedMessage {\n const ur = UR.fromURString(urString);\n return SealedMessage.fromUR(ur);\n }\n}\n","/**\n * Hash type enum for key derivation functions\n *\n * This enum represents the supported hash algorithms for HKDF and PBKDF2.\n *\n * CDDL:\n * ```cddl\n * HashType = SHA256 / SHA512\n * SHA256 = 0\n * SHA512 = 1\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/hash_type.rs\n */\n\nimport { type Cbor, cbor, expectNumber } from \"@bcts/dcbor\";\n\n/**\n * Enum representing supported hash types for key derivation.\n */\nexport enum HashType {\n /** SHA-256 hash algorithm */\n SHA256 = 0,\n /** SHA-512 hash algorithm */\n SHA512 = 1,\n}\n\n/**\n * Convert HashType to its string representation.\n */\nexport function hashTypeToString(hashType: HashType): string {\n switch (hashType) {\n case HashType.SHA256:\n return \"SHA256\";\n case HashType.SHA512:\n return \"SHA512\";\n default:\n throw new Error(`Unknown HashType: ${String(hashType)}`);\n }\n}\n\n/**\n * Convert HashType to CBOR.\n */\nexport function hashTypeToCbor(hashType: HashType): Cbor {\n return cbor(hashType);\n}\n\n/**\n * Parse HashType from CBOR.\n */\nexport function hashTypeFromCbor(cborValue: Cbor): HashType {\n const value = expectNumber(cborValue);\n switch (value) {\n case 0:\n return HashType.SHA256;\n case 1:\n return HashType.SHA512;\n default:\n throw new Error(`Invalid HashType: ${value}`);\n }\n}\n","/**\n * Key derivation method enum\n *\n * This enum represents the supported key derivation methods for encrypting keys.\n *\n * CDDL:\n * ```cddl\n * KeyDerivationMethod = HKDF / PBKDF2 / Scrypt / Argon2id / SSHAgent\n * HKDF = 0\n * PBKDF2 = 1\n * Scrypt = 2\n * Argon2id = 3\n * SSHAgent = 4\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/key_derivation_method.rs\n */\n\nimport { type Cbor, expectNumber } from \"@bcts/dcbor\";\n\n/**\n * Enum representing supported key derivation methods.\n */\nexport enum KeyDerivationMethod {\n /** HKDF (HMAC-based Key Derivation Function) - RFC 5869 */\n HKDF = 0,\n /** PBKDF2 (Password-Based Key Derivation Function 2) - RFC 8018 */\n PBKDF2 = 1,\n /** Scrypt - RFC 7914 */\n Scrypt = 2,\n /** Argon2id - RFC 9106 (default, most secure for passwords) */\n Argon2id = 3,\n /** SSH Agent - Uses SSH agent for key derivation */\n SSHAgent = 4,\n}\n\n/**\n * Returns the default key derivation method (Argon2id).\n */\nexport function defaultKeyDerivationMethod(): KeyDerivationMethod {\n return KeyDerivationMethod.Argon2id;\n}\n\n/**\n * Returns the zero-based index of the key derivation method.\n */\nexport function keyDerivationMethodIndex(method: KeyDerivationMethod): number {\n return method;\n}\n\n/**\n * Attempts to create a KeyDerivationMethod from a zero-based index.\n */\nexport function keyDerivationMethodFromIndex(index: number): KeyDerivationMethod | undefined {\n switch (index) {\n case 0:\n return KeyDerivationMethod.HKDF;\n case 1:\n return KeyDerivationMethod.PBKDF2;\n case 2:\n return KeyDerivationMethod.Scrypt;\n case 3:\n return KeyDerivationMethod.Argon2id;\n case 4:\n return KeyDerivationMethod.SSHAgent;\n default:\n return undefined;\n }\n}\n\n/**\n * Convert KeyDerivationMethod to its string representation.\n */\nexport function keyDerivationMethodToString(method: KeyDerivationMethod): string {\n switch (method) {\n case KeyDerivationMethod.HKDF:\n return \"HKDF\";\n case KeyDerivationMethod.PBKDF2:\n return \"PBKDF2\";\n case KeyDerivationMethod.Scrypt:\n return \"Scrypt\";\n case KeyDerivationMethod.Argon2id:\n return \"Argon2id\";\n case KeyDerivationMethod.SSHAgent:\n return \"SSHAgent\";\n default:\n throw new Error(`Unknown KeyDerivationMethod: ${String(method)}`);\n }\n}\n\n/**\n * Parse KeyDerivationMethod from CBOR.\n */\nexport function keyDerivationMethodFromCbor(cborValue: Cbor): KeyDerivationMethod {\n const value = expectNumber(cborValue);\n const method = keyDerivationMethodFromIndex(Number(value));\n if (method === undefined) {\n throw new Error(`Invalid KeyDerivationMethod index: ${value}`);\n }\n return method;\n}\n","/**\n * HKDF (HMAC-based Key Derivation Function) parameters\n *\n * HKDF is a key derivation function based on HMAC, defined in RFC 5869.\n * It is NOT suitable for password-based key derivation (use PBKDF2, Scrypt,\n * or Argon2id instead).\n *\n * CDDL:\n * ```cddl\n * HKDFParams = [0, Salt, HashType]\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/hkdf_params.rs\n */\n\nimport { type Cbor, cbor, expectArray, expectNumber, expectBytes } from \"@bcts/dcbor\";\nimport { hkdfHmacSha256, hkdfHmacSha512 } from \"@bcts/crypto\";\n\nimport { Salt } from \"../salt.js\";\nimport { Nonce } from \"../nonce.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { type EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { HashType, hashTypeToCbor, hashTypeFromCbor, hashTypeToString } from \"./hash-type.js\";\nimport { KeyDerivationMethod } from \"./key-derivation-method.js\";\nimport type { KeyDerivation } from \"./key-derivation.js\";\n\n/** Default salt length for key derivation */\nexport const SALT_LEN = 16;\n\n/**\n * HKDF parameters for key derivation.\n *\n * HKDF is suitable for deriving keys from high-entropy inputs (like other keys),\n * but NOT for password-based key derivation.\n */\nexport class HKDFParams implements KeyDerivation {\n static readonly INDEX = KeyDerivationMethod.HKDF;\n\n private readonly _salt: Salt;\n private readonly _hashType: HashType;\n\n private constructor(salt: Salt, hashType: HashType) {\n this._salt = salt;\n this._hashType = hashType;\n }\n\n /**\n * Create new HKDF parameters with default settings.\n * Uses a random 16-byte salt and SHA-256.\n */\n static new(): HKDFParams {\n return HKDFParams.newOpt(Salt.newWithLen(SALT_LEN), HashType.SHA256);\n }\n\n /**\n * Create HKDF parameters with custom settings.\n */\n static newOpt(salt: Salt, hashType: HashType): HKDFParams {\n return new HKDFParams(salt, hashType);\n }\n\n /** Returns the salt. */\n salt(): Salt {\n return this._salt;\n }\n\n /** Returns the hash type. */\n hashType(): HashType {\n return this._hashType;\n }\n\n /** Returns the method index for CBOR encoding. */\n index(): number {\n return HKDFParams.INDEX;\n }\n\n /**\n * Derive a key from the secret and encrypt the content key.\n */\n lock(contentKey: SymmetricKey, secret: Uint8Array): EncryptedMessage {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Encode the method parameters as AAD\n const encodedMethod = this.toCbor().toData();\n\n // Encrypt the content key using the derived key\n return derivedKey.encrypt(contentKey.data(), encodedMethod, Nonce.new());\n }\n\n /**\n * Derive a key from the secret and decrypt the content key.\n */\n unlock(encryptedMessage: EncryptedMessage, secret: Uint8Array): SymmetricKey {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Decrypt to get the content key\n const contentKeyData = derivedKey.decrypt(encryptedMessage);\n return SymmetricKey.fromData(contentKeyData);\n }\n\n private _deriveKey(secret: Uint8Array): Uint8Array {\n switch (this._hashType) {\n case HashType.SHA256:\n return hkdfHmacSha256(secret, this._salt.asBytes(), 32);\n case HashType.SHA512:\n return hkdfHmacSha512(secret, this._salt.asBytes(), 32);\n default:\n throw new Error(`Unknown hash type: ${String(this._hashType)}`);\n }\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `HKDF(${hashTypeToString(this._hashType)})`;\n }\n\n /**\n * Check equality with another HKDFParams.\n */\n equals(other: HKDFParams): boolean {\n return this._salt.equals(other._salt) && this._hashType === other._hashType;\n }\n\n // ============================================================================\n // CBOR Serialization\n // ============================================================================\n\n /**\n * Convert to CBOR.\n * Format: [0, Salt, HashType]\n */\n toCbor(): Cbor {\n return cbor([\n cbor(HKDFParams.INDEX),\n this._salt.untaggedCbor(),\n hashTypeToCbor(this._hashType),\n ]);\n }\n\n /**\n * Convert to CBOR binary data.\n */\n toCborData(): Uint8Array {\n return this.toCbor().toData();\n }\n\n /**\n * Parse from CBOR.\n */\n static fromCbor(cborValue: Cbor): HKDFParams {\n const array = expectArray(cborValue);\n\n if (array.length !== 3) {\n throw new Error(`Invalid HKDFParams: expected 3 elements, got ${array.length}`);\n }\n\n const index = expectNumber(array[0]);\n if (index !== HKDFParams.INDEX) {\n throw new Error(`Invalid HKDFParams index: expected ${HKDFParams.INDEX}, got ${index}`);\n }\n\n const saltData = expectBytes(array[1]);\n const salt = Salt.fromData(saltData);\n const hashType = hashTypeFromCbor(array[2]);\n\n return new HKDFParams(salt, hashType);\n }\n}\n","/**\n * PBKDF2 (Password-Based Key Derivation Function 2) parameters\n *\n * PBKDF2 is a key derivation function defined in RFC 8018 (PKCS #5 v2.1).\n * It is suitable for password-based key derivation.\n *\n * CDDL:\n * ```cddl\n * PBKDF2Params = [1, Salt, iterations: uint, HashType]\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/pbkdf2_params.rs\n */\n\nimport { type Cbor, cbor, expectArray, expectNumber, expectBytes } from \"@bcts/dcbor\";\nimport { pbkdf2HmacSha256, pbkdf2HmacSha512 } from \"@bcts/crypto\";\n\nimport { Salt } from \"../salt.js\";\nimport { Nonce } from \"../nonce.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { type EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { HashType, hashTypeToCbor, hashTypeFromCbor, hashTypeToString } from \"./hash-type.js\";\nimport { KeyDerivationMethod } from \"./key-derivation-method.js\";\nimport { SALT_LEN } from \"./hkdf-params.js\";\nimport type { KeyDerivation } from \"./key-derivation.js\";\n\n/** Default number of iterations for PBKDF2 */\nexport const DEFAULT_PBKDF2_ITERATIONS = 100_000;\n\n/**\n * PBKDF2 parameters for password-based key derivation.\n */\nexport class PBKDF2Params implements KeyDerivation {\n static readonly INDEX = KeyDerivationMethod.PBKDF2;\n\n private readonly _salt: Salt;\n private readonly _iterations: number;\n private readonly _hashType: HashType;\n\n private constructor(salt: Salt, iterations: number, hashType: HashType) {\n this._salt = salt;\n this._iterations = iterations;\n this._hashType = hashType;\n }\n\n /**\n * Create new PBKDF2 parameters with default settings.\n * Uses a random 16-byte salt, 100,000 iterations, and SHA-256.\n */\n static new(): PBKDF2Params {\n return PBKDF2Params.newOpt(\n Salt.newWithLen(SALT_LEN),\n DEFAULT_PBKDF2_ITERATIONS,\n HashType.SHA256,\n );\n }\n\n /**\n * Create PBKDF2 parameters with custom settings.\n */\n static newOpt(salt: Salt, iterations: number, hashType: HashType): PBKDF2Params {\n return new PBKDF2Params(salt, iterations, hashType);\n }\n\n /** Returns the salt. */\n salt(): Salt {\n return this._salt;\n }\n\n /** Returns the number of iterations. */\n iterations(): number {\n return this._iterations;\n }\n\n /** Returns the hash type. */\n hashType(): HashType {\n return this._hashType;\n }\n\n /** Returns the method index for CBOR encoding. */\n index(): number {\n return PBKDF2Params.INDEX;\n }\n\n /**\n * Derive a key from the secret and encrypt the content key.\n */\n lock(contentKey: SymmetricKey, secret: Uint8Array): EncryptedMessage {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Encode the method parameters as AAD\n const encodedMethod = this.toCbor().toData();\n\n // Encrypt the content key using the derived key\n return derivedKey.encrypt(contentKey.data(), encodedMethod, Nonce.new());\n }\n\n /**\n * Derive a key from the secret and decrypt the content key.\n */\n unlock(encryptedMessage: EncryptedMessage, secret: Uint8Array): SymmetricKey {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Decrypt to get the content key\n const contentKeyData = derivedKey.decrypt(encryptedMessage);\n return SymmetricKey.fromData(contentKeyData);\n }\n\n private _deriveKey(secret: Uint8Array): Uint8Array {\n switch (this._hashType) {\n case HashType.SHA256:\n return pbkdf2HmacSha256(secret, this._salt.asBytes(), this._iterations, 32);\n case HashType.SHA512:\n return pbkdf2HmacSha512(secret, this._salt.asBytes(), this._iterations, 32);\n default:\n throw new Error(`Unknown hash type: ${String(this._hashType)}`);\n }\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `PBKDF2(${hashTypeToString(this._hashType)})`;\n }\n\n /**\n * Check equality with another PBKDF2Params.\n */\n equals(other: PBKDF2Params): boolean {\n return (\n this._salt.equals(other._salt) &&\n this._iterations === other._iterations &&\n this._hashType === other._hashType\n );\n }\n\n // ============================================================================\n // CBOR Serialization\n // ============================================================================\n\n /**\n * Convert to CBOR.\n * Format: [1, Salt, iterations, HashType]\n */\n toCbor(): Cbor {\n return cbor([\n cbor(PBKDF2Params.INDEX),\n this._salt.untaggedCbor(),\n cbor(this._iterations),\n hashTypeToCbor(this._hashType),\n ]);\n }\n\n /**\n * Convert to CBOR binary data.\n */\n toCborData(): Uint8Array {\n return this.toCbor().toData();\n }\n\n /**\n * Parse from CBOR.\n */\n static fromCbor(cborValue: Cbor): PBKDF2Params {\n const array = expectArray(cborValue);\n\n if (array.length !== 4) {\n throw new Error(`Invalid PBKDF2Params: expected 4 elements, got ${array.length}`);\n }\n\n const index = expectNumber(array[0]);\n if (index !== PBKDF2Params.INDEX) {\n throw new Error(`Invalid PBKDF2Params index: expected ${PBKDF2Params.INDEX}, got ${index}`);\n }\n\n const saltData = expectBytes(array[1]);\n const salt = Salt.fromData(saltData);\n const iterations = Number(expectNumber(array[2]));\n const hashType = hashTypeFromCbor(array[3]);\n\n return new PBKDF2Params(salt, iterations, hashType);\n }\n}\n","/**\n * Scrypt parameters for password-based key derivation\n *\n * Scrypt is a memory-hard key derivation function defined in RFC 7914.\n * It is suitable for password-based key derivation and is more resistant\n * to hardware brute-force attacks than PBKDF2.\n *\n * CDDL:\n * ```cddl\n * ScryptParams = [2, Salt, log_n: uint, r: uint, p: uint]\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/scrypt_params.rs\n */\n\nimport { type Cbor, cbor, expectArray, expectNumber, expectBytes } from \"@bcts/dcbor\";\nimport { scryptOpt } from \"@bcts/crypto\";\n\nimport { Salt } from \"../salt.js\";\nimport { Nonce } from \"../nonce.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { type EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { KeyDerivationMethod } from \"./key-derivation-method.js\";\nimport { SALT_LEN } from \"./hkdf-params.js\";\nimport type { KeyDerivation } from \"./key-derivation.js\";\n\n/** Default log_n parameter (2^15 = 32768 iterations) */\nexport const DEFAULT_SCRYPT_LOG_N = 15;\n/** Default r parameter (block size) */\nexport const DEFAULT_SCRYPT_R = 8;\n/** Default p parameter (parallelism) */\nexport const DEFAULT_SCRYPT_P = 1;\n\n/**\n * Scrypt parameters for password-based key derivation.\n *\n * Parameters:\n * - log_n: CPU/memory cost parameter (N = 2^log_n)\n * - r: Block size parameter\n * - p: Parallelization parameter\n */\nexport class ScryptParams implements KeyDerivation {\n static readonly INDEX = KeyDerivationMethod.Scrypt;\n\n private readonly _salt: Salt;\n private readonly _logN: number;\n private readonly _r: number;\n private readonly _p: number;\n\n private constructor(salt: Salt, logN: number, r: number, p: number) {\n this._salt = salt;\n this._logN = logN;\n this._r = r;\n this._p = p;\n }\n\n /**\n * Create new Scrypt parameters with default settings.\n * Uses a random 16-byte salt, log_n=15, r=8, p=1.\n */\n static new(): ScryptParams {\n return ScryptParams.newOpt(\n Salt.newWithLen(SALT_LEN),\n DEFAULT_SCRYPT_LOG_N,\n DEFAULT_SCRYPT_R,\n DEFAULT_SCRYPT_P,\n );\n }\n\n /**\n * Create Scrypt parameters with custom settings.\n */\n static newOpt(salt: Salt, logN: number, r: number, p: number): ScryptParams {\n return new ScryptParams(salt, logN, r, p);\n }\n\n /** Returns the salt. */\n salt(): Salt {\n return this._salt;\n }\n\n /** Returns the log_n parameter. */\n logN(): number {\n return this._logN;\n }\n\n /** Returns the r parameter (block size). */\n r(): number {\n return this._r;\n }\n\n /** Returns the p parameter (parallelism). */\n p(): number {\n return this._p;\n }\n\n /** Returns the method index for CBOR encoding. */\n index(): number {\n return ScryptParams.INDEX;\n }\n\n /**\n * Derive a key from the secret and encrypt the content key.\n */\n lock(contentKey: SymmetricKey, secret: Uint8Array): EncryptedMessage {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Encode the method parameters as AAD\n const encodedMethod = this.toCbor().toData();\n\n // Encrypt the content key using the derived key\n return derivedKey.encrypt(contentKey.data(), encodedMethod, Nonce.new());\n }\n\n /**\n * Derive a key from the secret and decrypt the content key.\n */\n unlock(encryptedMessage: EncryptedMessage, secret: Uint8Array): SymmetricKey {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Decrypt to get the content key\n const contentKeyData = derivedKey.decrypt(encryptedMessage);\n return SymmetricKey.fromData(contentKeyData);\n }\n\n private _deriveKey(secret: Uint8Array): Uint8Array {\n return scryptOpt(secret, this._salt.asBytes(), 32, this._logN, this._r, this._p);\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return \"Scrypt\";\n }\n\n /**\n * Check equality with another ScryptParams.\n */\n equals(other: ScryptParams): boolean {\n return (\n this._salt.equals(other._salt) &&\n this._logN === other._logN &&\n this._r === other._r &&\n this._p === other._p\n );\n }\n\n // ============================================================================\n // CBOR Serialization\n // ============================================================================\n\n /**\n * Convert to CBOR.\n * Format: [2, Salt, log_n, r, p]\n */\n toCbor(): Cbor {\n return cbor([\n cbor(ScryptParams.INDEX),\n this._salt.untaggedCbor(),\n cbor(this._logN),\n cbor(this._r),\n cbor(this._p),\n ]);\n }\n\n /**\n * Convert to CBOR binary data.\n */\n toCborData(): Uint8Array {\n return this.toCbor().toData();\n }\n\n /**\n * Parse from CBOR.\n */\n static fromCbor(cborValue: Cbor): ScryptParams {\n const array = expectArray(cborValue);\n\n if (array.length !== 5) {\n throw new Error(`Invalid ScryptParams: expected 5 elements, got ${array.length}`);\n }\n\n const index = expectNumber(array[0]);\n if (index !== ScryptParams.INDEX) {\n throw new Error(`Invalid ScryptParams index: expected ${ScryptParams.INDEX}, got ${index}`);\n }\n\n const saltData = expectBytes(array[1]);\n const salt = Salt.fromData(saltData);\n const logN = Number(expectNumber(array[2]));\n const r = Number(expectNumber(array[3]));\n const p = Number(expectNumber(array[4]));\n\n return new ScryptParams(salt, logN, r, p);\n }\n}\n","/**\n * Argon2id parameters for password-based key derivation\n *\n * Argon2id is a memory-hard key derivation function defined in RFC 9106.\n * It combines Argon2i (resistant to side-channel attacks) and Argon2d\n * (resistant to GPU cracking attacks). It is the recommended choice for\n * password-based key derivation.\n *\n * CDDL:\n * ```cddl\n * Argon2idParams = [3, Salt]\n * ```\n *\n * Note: Argon2id uses sensible defaults for memory, iterations, and parallelism.\n * Only the salt is configurable in the CBOR encoding for simplicity.\n *\n * Ported from bc-components-rust/src/encrypted_key/argon2id_params.rs\n */\n\nimport { type Cbor, cbor, expectArray, expectNumber, expectBytes } from \"@bcts/dcbor\";\nimport { argon2id } from \"@bcts/crypto\";\n\nimport { Salt } from \"../salt.js\";\nimport { Nonce } from \"../nonce.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { type EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { KeyDerivationMethod } from \"./key-derivation-method.js\";\nimport { SALT_LEN } from \"./hkdf-params.js\";\nimport type { KeyDerivation } from \"./key-derivation.js\";\n\n/**\n * Argon2id parameters for password-based key derivation.\n *\n * This is the recommended method for password-based key derivation as it\n * provides the best protection against both GPU cracking and side-channel\n * attacks.\n */\nexport class Argon2idParams implements KeyDerivation {\n static readonly INDEX = KeyDerivationMethod.Argon2id;\n\n private readonly _salt: Salt;\n\n private constructor(salt: Salt) {\n this._salt = salt;\n }\n\n /**\n * Create new Argon2id parameters with default settings.\n * Uses a random 16-byte salt.\n */\n static new(): Argon2idParams {\n return Argon2idParams.newOpt(Salt.newWithLen(SALT_LEN));\n }\n\n /**\n * Create Argon2id parameters with a custom salt.\n */\n static newOpt(salt: Salt): Argon2idParams {\n return new Argon2idParams(salt);\n }\n\n /** Returns the salt. */\n salt(): Salt {\n return this._salt;\n }\n\n /** Returns the method index for CBOR encoding. */\n index(): number {\n return Argon2idParams.INDEX;\n }\n\n /**\n * Derive a key from the secret and encrypt the content key.\n */\n lock(contentKey: SymmetricKey, secret: Uint8Array): EncryptedMessage {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Encode the method parameters as AAD\n const encodedMethod = this.toCbor().toData();\n\n // Encrypt the content key using the derived key\n return derivedKey.encrypt(contentKey.data(), encodedMethod, Nonce.new());\n }\n\n /**\n * Derive a key from the secret and decrypt the content key.\n */\n unlock(encryptedMessage: EncryptedMessage, secret: Uint8Array): SymmetricKey {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Decrypt to get the content key\n const contentKeyData = derivedKey.decrypt(encryptedMessage);\n return SymmetricKey.fromData(contentKeyData);\n }\n\n private _deriveKey(secret: Uint8Array): Uint8Array {\n return argon2id(secret, this._salt.asBytes(), 32);\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return \"Argon2id\";\n }\n\n /**\n * Check equality with another Argon2idParams.\n */\n equals(other: Argon2idParams): boolean {\n return this._salt.equals(other._salt);\n }\n\n // ============================================================================\n // CBOR Serialization\n // ============================================================================\n\n /**\n * Convert to CBOR.\n * Format: [3, Salt]\n */\n toCbor(): Cbor {\n return cbor([cbor(Argon2idParams.INDEX), this._salt.untaggedCbor()]);\n }\n\n /**\n * Convert to CBOR binary data.\n */\n toCborData(): Uint8Array {\n return this.toCbor().toData();\n }\n\n /**\n * Parse from CBOR.\n */\n static fromCbor(cborValue: Cbor): Argon2idParams {\n const array = expectArray(cborValue);\n\n if (array.length !== 2) {\n throw new Error(`Invalid Argon2idParams: expected 2 elements, got ${array.length}`);\n }\n\n const index = expectNumber(array[0]);\n if (index !== Argon2idParams.INDEX) {\n throw new Error(\n `Invalid Argon2idParams index: expected ${Argon2idParams.INDEX}, got ${index}`,\n );\n }\n\n const saltData = expectBytes(array[1]);\n const salt = Salt.fromData(saltData);\n\n return new Argon2idParams(salt);\n }\n}\n","/**\n * SSH Agent key derivation parameters\n *\n * SSH Agent uses an SSH agent daemon for key derivation. The agent signs\n * a challenge derived from the salt to produce the encryption key.\n *\n * CDDL:\n * ```cddl\n * SSHAgentParams = [4, Salt, id: tstr]\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/ssh_agent_params.rs\n */\n\nimport { type Cbor, cbor, expectArray, expectNumber, expectBytes, expectText } from \"@bcts/dcbor\";\n\nimport { Salt } from \"../salt.js\";\nimport type { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport type { EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { KeyDerivationMethod } from \"./key-derivation-method.js\";\nimport type { KeyDerivation } from \"./key-derivation.js\";\nimport { CryptoError } from \"../error.js\";\n\n/** Default salt length for SSH agent key derivation */\nexport const SALT_LEN = 16;\n\n/**\n * SSH Agent parameters for key derivation.\n *\n * This method uses an SSH agent daemon to derive encryption keys.\n * The agent signs a challenge derived from the salt using the specified\n * SSH key identity, and the signature is used to derive the encryption key.\n *\n * **Note:** SSH agent communication requires platform-specific support and\n * may not be available in all JavaScript environments. The lock/unlock\n * methods will throw an error if SSH agent support is not available.\n */\nexport class SSHAgentParams implements KeyDerivation {\n static readonly INDEX = KeyDerivationMethod.SSHAgent;\n\n private readonly _salt: Salt;\n private readonly _id: string;\n\n private constructor(salt: Salt, id: string) {\n this._salt = salt;\n this._id = id;\n }\n\n /**\n * Create new SSH agent parameters with default salt and specified key ID.\n *\n * @param id - The SSH key identity (usually the key comment or public key fingerprint)\n */\n static new(id: string): SSHAgentParams {\n return SSHAgentParams.newOpt(Salt.newWithLen(SALT_LEN), id);\n }\n\n /**\n * Create SSH agent parameters with custom salt and key ID.\n *\n * @param salt - The salt for key derivation\n * @param id - The SSH key identity\n */\n static newOpt(salt: Salt, id: string): SSHAgentParams {\n return new SSHAgentParams(salt, id);\n }\n\n /** Returns the salt. */\n salt(): Salt {\n return this._salt;\n }\n\n /** Returns the SSH key identity. */\n id(): string {\n return this._id;\n }\n\n /** Returns the method index for CBOR encoding. */\n index(): number {\n return SSHAgentParams.INDEX;\n }\n\n /**\n * Derive a key using SSH agent and encrypt the content key.\n *\n * **Note:** This method requires SSH agent support which is not yet\n * implemented in this TypeScript port. Use an alternative key derivation\n * method or implement SSH agent communication for your environment.\n *\n * @throws CryptoError - SSH agent support is not available\n */\n lock(_contentKey: SymmetricKey, _secret: Uint8Array): EncryptedMessage {\n throw CryptoError.sshAgent(\n \"SSH agent key derivation is not yet implemented in this TypeScript port. \" +\n \"Use HKDF, PBKDF2, Scrypt, or Argon2id instead.\",\n );\n }\n\n /**\n * Derive a key using SSH agent and decrypt the content key.\n *\n * **Note:** This method requires SSH agent support which is not yet\n * implemented in this TypeScript port. Use an alternative key derivation\n * method or implement SSH agent communication for your environment.\n *\n * @throws CryptoError - SSH agent support is not available\n */\n unlock(_encryptedMessage: EncryptedMessage, _secret: Uint8Array): SymmetricKey {\n throw CryptoError.sshAgent(\n \"SSH agent key derivation is not yet implemented in this TypeScript port. \" +\n \"Use HKDF, PBKDF2, Scrypt, or Argon2id instead.\",\n );\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `SSHAgent(id: \"${this._id}\")`;\n }\n\n /**\n * Check equality with another SSHAgentParams.\n */\n equals(other: SSHAgentParams): boolean {\n return this._salt.equals(other._salt) && this._id === other._id;\n }\n\n // ============================================================================\n // CBOR Serialization\n // ============================================================================\n\n /**\n * Convert to CBOR.\n * Format: [4, Salt, id: tstr]\n */\n toCbor(): Cbor {\n return cbor([cbor(SSHAgentParams.INDEX), this._salt.untaggedCbor(), cbor(this._id)]);\n }\n\n /**\n * Convert to CBOR binary data.\n */\n toCborData(): Uint8Array {\n return this.toCbor().toData();\n }\n\n /**\n * Parse from CBOR.\n */\n static fromCbor(cborValue: Cbor): SSHAgentParams {\n const array = expectArray(cborValue);\n\n if (array.length !== 3) {\n throw new Error(`Invalid SSHAgentParams: expected 3 elements, got ${array.length}`);\n }\n\n const index = expectNumber(array[0]);\n if (index !== SSHAgentParams.INDEX) {\n throw new Error(\n `Invalid SSHAgentParams index: expected ${SSHAgentParams.INDEX}, got ${index}`,\n );\n }\n\n const saltData = expectBytes(array[1]);\n const salt = Salt.fromData(saltData);\n const id = expectText(array[2]);\n\n return new SSHAgentParams(salt, id);\n }\n}\n","/**\n * Key derivation parameters union type\n *\n * This type represents the derivation parameters for all supported methods.\n * It provides a unified interface for locking and unlocking keys regardless\n * of the underlying derivation method.\n *\n * Ported from bc-components-rust/src/encrypted_key/key_derivation_params.rs\n */\n\nimport { type Cbor, expectArray, expectNumber } from \"@bcts/dcbor\";\n\nimport type { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport type { EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { KeyDerivationMethod, keyDerivationMethodFromIndex } from \"./key-derivation-method.js\";\nimport { HKDFParams } from \"./hkdf-params.js\";\nimport { PBKDF2Params } from \"./pbkdf2-params.js\";\nimport { ScryptParams } from \"./scrypt-params.js\";\nimport { Argon2idParams } from \"./argon2id-params.js\";\nimport { SSHAgentParams } from \"./ssh-agent-params.js\";\n\n/**\n * Union type representing key derivation parameters.\n *\n * Use the `method()` function to get the derivation method, and\n * `lock()`/`unlock()` for key operations.\n */\nexport type KeyDerivationParams =\n | { type: \"hkdf\"; params: HKDFParams }\n | { type: \"pbkdf2\"; params: PBKDF2Params }\n | { type: \"scrypt\"; params: ScryptParams }\n | { type: \"argon2id\"; params: Argon2idParams }\n | { type: \"sshagent\"; params: SSHAgentParams };\n\n/**\n * Create HKDF derivation parameters.\n */\nexport function hkdfParams(params?: HKDFParams): KeyDerivationParams {\n return { type: \"hkdf\", params: params ?? HKDFParams.new() };\n}\n\n/**\n * Create PBKDF2 derivation parameters.\n */\nexport function pbkdf2Params(params?: PBKDF2Params): KeyDerivationParams {\n return { type: \"pbkdf2\", params: params ?? PBKDF2Params.new() };\n}\n\n/**\n * Create Scrypt derivation parameters.\n */\nexport function scryptParams(params?: ScryptParams): KeyDerivationParams {\n return { type: \"scrypt\", params: params ?? ScryptParams.new() };\n}\n\n/**\n * Create Argon2id derivation parameters.\n */\nexport function argon2idParams(params?: Argon2idParams): KeyDerivationParams {\n return { type: \"argon2id\", params: params ?? Argon2idParams.new() };\n}\n\n/**\n * Create SSH agent derivation parameters.\n *\n * @param idOrParams - Either an SSH key identity string or SSHAgentParams instance\n */\nexport function sshAgentParams(idOrParams: string | SSHAgentParams): KeyDerivationParams {\n if (typeof idOrParams === \"string\") {\n return { type: \"sshagent\", params: SSHAgentParams.new(idOrParams) };\n }\n return { type: \"sshagent\", params: idOrParams };\n}\n\n/**\n * Create default key derivation parameters (Argon2id).\n */\nexport function defaultKeyDerivationParams(): KeyDerivationParams {\n return argon2idParams();\n}\n\n/**\n * Get the key derivation method for the given parameters.\n */\nexport function keyDerivationParamsMethod(kdp: KeyDerivationParams): KeyDerivationMethod {\n switch (kdp.type) {\n case \"hkdf\":\n return KeyDerivationMethod.HKDF;\n case \"pbkdf2\":\n return KeyDerivationMethod.PBKDF2;\n case \"scrypt\":\n return KeyDerivationMethod.Scrypt;\n case \"argon2id\":\n return KeyDerivationMethod.Argon2id;\n case \"sshagent\":\n return KeyDerivationMethod.SSHAgent;\n }\n}\n\n/**\n * Check if the parameters use a password-based method.\n * Password-based methods (PBKDF2, Scrypt, Argon2id) are designed for\n * low-entropy secrets like passwords.\n */\nexport function isPasswordBased(kdp: KeyDerivationParams): boolean {\n return kdp.type === \"pbkdf2\" || kdp.type === \"scrypt\" || kdp.type === \"argon2id\";\n}\n\n/**\n * Check if the parameters use SSH Agent for key derivation.\n *\n * Note: SSH Agent key derivation is not yet functional in TypeScript.\n * This function is useful for detecting envelopes locked by other\n * implementations (e.g., Rust).\n */\nexport function isSshAgent(kdp: KeyDerivationParams): boolean {\n return kdp.type === \"sshagent\";\n}\n\n/**\n * Lock (encrypt) a content key using the derived key.\n */\nexport function lockWithParams(\n kdp: KeyDerivationParams,\n contentKey: SymmetricKey,\n secret: Uint8Array,\n): EncryptedMessage {\n switch (kdp.type) {\n case \"hkdf\":\n return kdp.params.lock(contentKey, secret);\n case \"pbkdf2\":\n return kdp.params.lock(contentKey, secret);\n case \"scrypt\":\n return kdp.params.lock(contentKey, secret);\n case \"argon2id\":\n return kdp.params.lock(contentKey, secret);\n case \"sshagent\":\n return kdp.params.lock(contentKey, secret);\n }\n}\n\n/**\n * Convert KeyDerivationParams to CBOR.\n */\nexport function keyDerivationParamsToCbor(kdp: KeyDerivationParams): Cbor {\n switch (kdp.type) {\n case \"hkdf\":\n return kdp.params.toCbor();\n case \"pbkdf2\":\n return kdp.params.toCbor();\n case \"scrypt\":\n return kdp.params.toCbor();\n case \"argon2id\":\n return kdp.params.toCbor();\n case \"sshagent\":\n return kdp.params.toCbor();\n }\n}\n\n/**\n * Convert KeyDerivationParams to CBOR binary data.\n */\nexport function keyDerivationParamsToCborData(kdp: KeyDerivationParams): Uint8Array {\n return keyDerivationParamsToCbor(kdp).toData();\n}\n\n/**\n * Get string representation of KeyDerivationParams.\n */\nexport function keyDerivationParamsToString(kdp: KeyDerivationParams): string {\n switch (kdp.type) {\n case \"hkdf\":\n return kdp.params.toString();\n case \"pbkdf2\":\n return kdp.params.toString();\n case \"scrypt\":\n return kdp.params.toString();\n case \"argon2id\":\n return kdp.params.toString();\n case \"sshagent\":\n return kdp.params.toString();\n }\n}\n\n/**\n * Parse KeyDerivationParams from CBOR.\n */\nexport function keyDerivationParamsFromCbor(cborValue: Cbor): KeyDerivationParams {\n const array = expectArray(cborValue);\n if (array.length === 0) {\n throw new Error(\"Invalid KeyDerivationParams: empty array\");\n }\n\n const index = expectNumber(array[0]);\n const method = keyDerivationMethodFromIndex(Number(index));\n\n if (method === undefined) {\n throw new Error(`Invalid KeyDerivationMethod index: ${index}`);\n }\n\n switch (method) {\n case KeyDerivationMethod.HKDF:\n return { type: \"hkdf\", params: HKDFParams.fromCbor(cborValue) };\n case KeyDerivationMethod.PBKDF2:\n return { type: \"pbkdf2\", params: PBKDF2Params.fromCbor(cborValue) };\n case KeyDerivationMethod.Scrypt:\n return { type: \"scrypt\", params: ScryptParams.fromCbor(cborValue) };\n case KeyDerivationMethod.Argon2id:\n return { type: \"argon2id\", params: Argon2idParams.fromCbor(cborValue) };\n case KeyDerivationMethod.SSHAgent:\n return { type: \"sshagent\", params: SSHAgentParams.fromCbor(cborValue) };\n }\n}\n","/**\n * Encrypted key for secure symmetric key storage\n *\n * `EncryptedKey` provides symmetric encryption and decryption of content keys\n * using various key derivation methods (HKDF, PBKDF2, Scrypt, Argon2id).\n *\n * The form of an `EncryptedKey` is an `EncryptedMessage` that contains the\n * encrypted content key, with its Additional Authenticated Data (AAD) being\n * the CBOR encoding of the key derivation method and parameters.\n *\n * CDDL:\n * ```cddl\n * EncryptedKey = #6.40027(EncryptedMessage)\n *\n * EncryptedMessage =\n * #6.40002([ ciphertext: bstr, nonce: bstr, auth: bstr, aad: bstr .cbor KeyDerivation ])\n *\n * KeyDerivation = HKDFParams / PBKDF2Params / ScryptParams / Argon2idParams\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/encrypted_key_impl.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n createTaggedCbor,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n validateTag,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { ENCRYPTED_KEY as TAG_ENCRYPTED_KEY } from \"@bcts/tags\";\n\nimport { type SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { CryptoError } from \"../error.js\";\nimport { KeyDerivationMethod } from \"./key-derivation-method.js\";\nimport {\n type KeyDerivationParams,\n hkdfParams,\n pbkdf2Params,\n scryptParams,\n argon2idParams,\n keyDerivationParamsMethod,\n keyDerivationParamsToString,\n keyDerivationParamsFromCbor,\n lockWithParams,\n isPasswordBased,\n isSshAgent,\n} from \"./key-derivation-params.js\";\n\n/**\n * Encrypted key providing secure storage of symmetric keys.\n *\n * Use `lock()` to encrypt a content key with a password or secret,\n * and `unlock()` to decrypt it.\n */\nexport class EncryptedKey\n implements CborTaggedEncodable, CborTaggedDecodable<EncryptedKey>, UREncodable\n{\n private readonly _params: KeyDerivationParams;\n private readonly _encryptedMessage: EncryptedMessage;\n\n private constructor(params: KeyDerivationParams, encryptedMessage: EncryptedMessage) {\n this._params = params;\n this._encryptedMessage = encryptedMessage;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Lock (encrypt) a content key using custom derivation parameters.\n *\n * @param params - The key derivation parameters to use\n * @param secret - The secret (password or key material) to derive from\n * @param contentKey - The symmetric key to encrypt\n * @returns The encrypted key\n */\n static lockOpt(\n params: KeyDerivationParams,\n secret: Uint8Array,\n contentKey: SymmetricKey,\n ): EncryptedKey {\n const encryptedMessage = lockWithParams(params, contentKey, secret);\n return new EncryptedKey(params, encryptedMessage);\n }\n\n /**\n * Lock (encrypt) a content key using a specific derivation method with defaults.\n *\n * @param method - The key derivation method to use\n * @param secret - The secret (password or key material) to derive from\n * @param contentKey - The symmetric key to encrypt\n * @returns The encrypted key\n */\n static lock(\n method: KeyDerivationMethod,\n secret: Uint8Array,\n contentKey: SymmetricKey,\n ): EncryptedKey {\n let params: KeyDerivationParams;\n\n switch (method) {\n case KeyDerivationMethod.HKDF:\n params = hkdfParams();\n break;\n case KeyDerivationMethod.PBKDF2:\n params = pbkdf2Params();\n break;\n case KeyDerivationMethod.Scrypt:\n params = scryptParams();\n break;\n case KeyDerivationMethod.Argon2id:\n params = argon2idParams();\n break;\n case KeyDerivationMethod.SSHAgent:\n throw new Error(\n \"SSH Agent key derivation cannot be used with lock() - use lockOpt() with sshAgentParams() instead\",\n );\n }\n\n return EncryptedKey.lockOpt(params, secret, contentKey);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the encrypted message.\n */\n encryptedMessage(): EncryptedMessage {\n return this._encryptedMessage;\n }\n\n /**\n * Returns the key derivation parameters.\n */\n params(): KeyDerivationParams {\n return this._params;\n }\n\n /**\n * Returns the key derivation method.\n */\n method(): KeyDerivationMethod {\n return keyDerivationParamsMethod(this._params);\n }\n\n /**\n * Check if this uses a password-based key derivation method.\n */\n isPasswordBased(): boolean {\n return isPasswordBased(this._params);\n }\n\n /**\n * Check if this uses SSH Agent for key derivation.\n *\n * Note: SSH Agent key derivation is not yet functional in TypeScript.\n * This method is useful for detecting envelopes locked by other\n * implementations (e.g., Rust).\n */\n isSshAgent(): boolean {\n return isSshAgent(this._params);\n }\n\n /**\n * Unlock (decrypt) the content key.\n *\n * @param secret - The secret (password or key material) used to lock\n * @returns The decrypted symmetric key\n * @throws CryptoError if decryption fails (wrong password, tampered data, etc.)\n */\n unlock(secret: Uint8Array): SymmetricKey {\n // Get the AAD from the encrypted message, which contains the derivation params\n const aad = this._encryptedMessage.aad();\n if (aad.length === 0) {\n throw CryptoError.invalidData(\"Missing AAD in EncryptedKey\");\n }\n\n // Parse the derivation parameters from AAD\n const paramsCbor = decodeCbor(aad);\n const params = keyDerivationParamsFromCbor(paramsCbor);\n\n // Unlock using the parsed parameters\n switch (params.type) {\n case \"hkdf\":\n return params.params.unlock(this._encryptedMessage, secret);\n case \"pbkdf2\":\n return params.params.unlock(this._encryptedMessage, secret);\n case \"scrypt\":\n return params.params.unlock(this._encryptedMessage, secret);\n case \"argon2id\":\n return params.params.unlock(this._encryptedMessage, secret);\n case \"sshagent\":\n return params.params.unlock(this._encryptedMessage, secret);\n }\n }\n\n /**\n * Check equality with another EncryptedKey.\n */\n equals(other: EncryptedKey): boolean {\n return this._encryptedMessage.equals(other._encryptedMessage);\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `EncryptedKey(${keyDerivationParamsToString(this._params)})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with EncryptedKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_ENCRYPTED_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n * The EncryptedMessage is encoded with its own tag (40002).\n */\n untaggedCbor(): Cbor {\n return this._encryptedMessage.taggedCbor();\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an EncryptedKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): EncryptedKey {\n // The untagged content is a tagged EncryptedMessage\n const encryptedMessage = EncryptedMessage.fromTaggedCbor(cborValue);\n\n // Parse the derivation parameters from AAD\n const aad = encryptedMessage.aad();\n if (aad.length === 0) {\n throw CryptoError.invalidData(\"Missing AAD in EncryptedKey\");\n }\n const paramsCbor = decodeCbor(aad);\n const params = keyDerivationParamsFromCbor(paramsCbor);\n\n return new EncryptedKey(params, encryptedMessage);\n }\n\n /**\n * Creates an EncryptedKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): EncryptedKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): EncryptedKey {\n // Create a dummy instance for the method\n const dummyParams = hkdfParams();\n const dummyMessage = EncryptedMessage.new(\n new Uint8Array(32),\n new Uint8Array(0),\n // @ts-expect-error - Using internal method for dummy\n { data: () => new Uint8Array(12) },\n new Uint8Array(16),\n );\n const dummy = new EncryptedKey(dummyParams, dummyMessage);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): EncryptedKey {\n const cborValue = decodeCbor(data);\n return EncryptedKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): EncryptedKey {\n const cborValue = decodeCbor(data);\n const dummyParams = hkdfParams();\n const dummyMessage = EncryptedMessage.new(\n new Uint8Array(32),\n new Uint8Array(0),\n // @ts-expect-error - Using internal method for dummy\n { data: () => new Uint8Array(12) },\n new Uint8Array(16),\n );\n const dummy = new EncryptedKey(dummyParams, dummyMessage);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_ENCRYPTED_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_ENCRYPTED_KEY.name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an EncryptedKey from a UR.\n */\n static fromUR(ur: UR): EncryptedKey {\n const name = TAG_ENCRYPTED_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_ENCRYPTED_KEY.name is undefined\");\n }\n ur.checkType(name);\n return EncryptedKey.fromUntaggedCborData(ur.cbor().toData());\n }\n\n /**\n * Creates an EncryptedKey from a UR string.\n */\n static fromURString(urString: string): EncryptedKey {\n const ur = UR.fromURString(urString);\n return EncryptedKey.fromUR(ur);\n }\n}\n","/**\n * PublicKeys - Container for signing and encapsulation public keys\n *\n * PublicKeys combines a SigningPublicKey (for signature verification) and an\n * EncapsulationPublicKey (for key agreement/encryption) into a single unit.\n *\n * This is the public counterpart to PrivateKeys.\n *\n * # CBOR Serialization\n *\n * PublicKeys is serialized with tag 40017:\n * ```\n * #6.40017([<SigningPublicKey>, <EncapsulationPublicKey>])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `crypto-pubkeys`\n *\n * Ported from bc-components-rust/src/public_keys.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { PUBLIC_KEYS as TAG_PUBLIC_KEYS } from \"@bcts/tags\";\n\nimport { SigningPublicKey } from \"./signing/signing-public-key.js\";\nimport { EncapsulationPublicKey } from \"./encapsulation/encapsulation-public-key.js\";\nimport type { EncapsulationCiphertext } from \"./encapsulation/encapsulation-ciphertext.js\";\nimport type { SymmetricKey } from \"./symmetric/symmetric-key.js\";\nimport type { Signature } from \"./signing/signature.js\";\nimport type { Verifier } from \"./signing/signer.js\";\nimport type { Encrypter } from \"./encrypter.js\";\nimport { Reference, type ReferenceProvider } from \"./reference.js\";\nimport { Digest } from \"./digest.js\";\n\n/**\n * Trait for types that provide access to a PublicKeys container.\n *\n * This is useful for types that wrap or contain public keys and need\n * to provide access to the underlying key material.\n */\nexport interface PublicKeysProvider {\n /**\n * Returns the PublicKeys container.\n */\n publicKeys(): PublicKeys;\n}\n\n/**\n * PublicKeys - Container for a signing public key and an encapsulation public key.\n *\n * This type provides a convenient way to share public keys for both\n * signature verification and encryption operations.\n */\nexport class PublicKeys\n implements\n Verifier,\n Encrypter,\n ReferenceProvider,\n CborTaggedEncodable,\n CborTaggedDecodable<PublicKeys>,\n UREncodable\n{\n private readonly _signingPublicKey: SigningPublicKey;\n private readonly _encapsulationPublicKey: EncapsulationPublicKey;\n\n private constructor(\n signingPublicKey: SigningPublicKey,\n encapsulationPublicKey: EncapsulationPublicKey,\n ) {\n this._signingPublicKey = signingPublicKey;\n this._encapsulationPublicKey = encapsulationPublicKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new PublicKeys container with the given keys.\n */\n static new(\n signingPublicKey: SigningPublicKey,\n encapsulationPublicKey: EncapsulationPublicKey,\n ): PublicKeys {\n return new PublicKeys(signingPublicKey, encapsulationPublicKey);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the signing public key.\n */\n signingPublicKey(): SigningPublicKey {\n return this._signingPublicKey;\n }\n\n /**\n * Returns the encapsulation public key.\n *\n * Note: Named to match Rust's API (which has a typo but we maintain compatibility)\n */\n encapsulationPublicKey(): EncapsulationPublicKey {\n return this._encapsulationPublicKey;\n }\n\n // ============================================================================\n // Verifier Interface\n // ============================================================================\n\n /**\n * Verify a signature against a message.\n */\n verify(signature: Signature, message: Uint8Array): boolean {\n return this._signingPublicKey.verify(signature, message);\n }\n\n // ============================================================================\n // Encrypter Interface\n // ============================================================================\n\n /**\n * Encapsulate a new shared secret using the encapsulation public key.\n *\n * This implements the Encrypter interface, allowing PublicKeys to be used\n * in encryption contexts where a shared secret needs to be generated.\n *\n * @returns A tuple of [SymmetricKey, EncapsulationCiphertext]\n */\n encapsulateNewSharedSecret(): [SymmetricKey, EncapsulationCiphertext] {\n return this._encapsulationPublicKey.encapsulateNewSharedSecret();\n }\n\n // ============================================================================\n // ReferenceProvider Interface\n // ============================================================================\n\n /**\n * Returns a unique reference to this PublicKeys instance.\n *\n * The reference is derived from the SHA-256 hash of the tagged CBOR\n * representation, providing a unique, content-addressable identifier.\n */\n reference(): Reference {\n const digest = Digest.fromImage(this.taggedCborData());\n return Reference.from(digest);\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another PublicKeys.\n */\n equals(other: PublicKeys): boolean {\n return (\n this._signingPublicKey.equals(other._signingPublicKey) &&\n this._encapsulationPublicKey.equals(other._encapsulationPublicKey)\n );\n }\n\n /**\n * Get string representation.\n *\n * Format matches Rust: `PublicKeys(<short_reference>)`\n */\n toString(): string {\n return `PublicKeys(${this.reference().shortReference(\"hex\")})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with PublicKeys.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_PUBLIC_KEYS.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [<SigningPublicKey>, <EncapsulationPublicKey>]\n */\n untaggedCbor(): Cbor {\n return cbor([this._signingPublicKey.taggedCbor(), this._encapsulationPublicKey.taggedCbor()]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a PublicKeys by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): PublicKeys {\n const elements = expectArray(cborValue);\n\n if (elements.length !== 2) {\n throw new Error(`PublicKeys must have 2 elements, got ${elements.length}`);\n }\n\n const signingPublicKey = SigningPublicKey.fromTaggedCbor(elements[0]);\n const encapsulationPublicKey = EncapsulationPublicKey.fromTaggedCbor(elements[1]);\n\n return new PublicKeys(signingPublicKey, encapsulationPublicKey);\n }\n\n /**\n * Creates a PublicKeys by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): PublicKeys {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): PublicKeys {\n // We need a dummy instance to call instance methods\n // Create minimal valid keys for this purpose\n const signingKeyPrefix = new Uint8Array([0x82, 0x02, 0x58, 0x20]);\n const signingKeyData = new Uint8Array(36);\n signingKeyData.set(signingKeyPrefix, 0);\n const signingKey = SigningPublicKey.fromUntaggedCborData(signingKeyData);\n\n const encapsulationKeyPrefix = new Uint8Array([0x58, 0x20]);\n const encapsulationKeyData = new Uint8Array(34);\n encapsulationKeyData.set(encapsulationKeyPrefix, 0);\n const encapsulationKey = EncapsulationPublicKey.fromUntaggedCborData(encapsulationKeyData);\n\n const dummy = new PublicKeys(signingKey, encapsulationKey);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): PublicKeys {\n const cborValue = decodeCbor(data);\n return PublicKeys.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): PublicKeys {\n const cborValue = decodeCbor(data);\n // We need a dummy instance to call instance methods\n const signingKeyPrefix = new Uint8Array([0x82, 0x02, 0x58, 0x20]);\n const signingKeyData = new Uint8Array(36);\n signingKeyData.set(signingKeyPrefix, 0);\n const signingKey = SigningPublicKey.fromUntaggedCborData(signingKeyData);\n\n const encapsulationKeyPrefix = new Uint8Array([0x58, 0x20]);\n const encapsulationKeyData = new Uint8Array(34);\n encapsulationKeyData.set(encapsulationKeyPrefix, 0);\n const encapsulationKey = EncapsulationPublicKey.fromUntaggedCborData(encapsulationKeyData);\n\n const dummy = new PublicKeys(signingKey, encapsulationKey);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_PUBLIC_KEYS.name;\n if (name === undefined) {\n throw new Error(\"PUBLIC_KEYS tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a PublicKeys from a UR.\n */\n static fromUR(ur: UR): PublicKeys {\n if (ur.urTypeStr() !== TAG_PUBLIC_KEYS.name) {\n throw new Error(`Expected UR type ${TAG_PUBLIC_KEYS.name}, got ${ur.urTypeStr()}`);\n }\n // We need a dummy instance to call instance methods\n const signingKeyPrefix = new Uint8Array([0x82, 0x02, 0x58, 0x20]);\n const signingKeyData = new Uint8Array(36);\n signingKeyData.set(signingKeyPrefix, 0);\n const signingKey = SigningPublicKey.fromUntaggedCborData(signingKeyData);\n\n const encapsulationKeyPrefix = new Uint8Array([0x58, 0x20]);\n const encapsulationKeyData = new Uint8Array(34);\n encapsulationKeyData.set(encapsulationKeyPrefix, 0);\n const encapsulationKey = EncapsulationPublicKey.fromUntaggedCborData(encapsulationKeyData);\n\n const dummy = new PublicKeys(signingKey, encapsulationKey);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a PublicKeys from a UR string.\n */\n static fromURString(urString: string): PublicKeys {\n const ur = UR.fromURString(urString);\n return PublicKeys.fromUR(ur);\n }\n}\n","/**\n * PrivateKeys - Container for signing and encapsulation private keys\n *\n * PrivateKeys combines a SigningPrivateKey (for digital signatures) and an\n * EncapsulationPrivateKey (for key agreement/encryption) into a single unit.\n *\n * # CBOR Serialization\n *\n * PrivateKeys is serialized with tag 40013:\n * ```\n * #6.40013([<SigningPrivateKey>, <EncapsulationPrivateKey>])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `crypto-prvkeys`\n *\n * Ported from bc-components-rust/src/private_keys.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { PRIVATE_KEYS as TAG_PRIVATE_KEYS } from \"@bcts/tags\";\n\nimport { SigningPrivateKey } from \"./signing/signing-private-key.js\";\nimport { EncapsulationPrivateKey } from \"./encapsulation/encapsulation-private-key.js\";\nimport { PublicKeys } from \"./public-keys.js\";\nimport type { SymmetricKey } from \"./symmetric/symmetric-key.js\";\nimport type { EncapsulationCiphertext } from \"./encapsulation/encapsulation-ciphertext.js\";\nimport type { Signature } from \"./signing/signature.js\";\nimport type { Signer } from \"./signing/signer.js\";\nimport type { SigningOptions } from \"./signing/signature-scheme.js\";\nimport type { Decrypter } from \"./encrypter.js\";\nimport { Reference, type ReferenceProvider } from \"./reference.js\";\nimport { Digest } from \"./digest.js\";\n\n/**\n * Trait for types that provide access to a PrivateKeys container.\n *\n * This is useful for types that wrap or contain private keys and need\n * to provide access to the underlying key material.\n */\nexport interface PrivateKeysProvider {\n /**\n * Returns the PrivateKeys container.\n */\n privateKeys(): PrivateKeys;\n}\n\n/**\n * PrivateKeys - Container for a signing key and an encapsulation key.\n *\n * This type provides a convenient way to manage a pair of private keys\n * for both signing and encryption operations.\n */\nexport class PrivateKeys\n implements\n Signer,\n Decrypter,\n ReferenceProvider,\n CborTaggedEncodable,\n CborTaggedDecodable<PrivateKeys>,\n UREncodable\n{\n private readonly _signingPrivateKey: SigningPrivateKey;\n private readonly _encapsulationPrivateKey: EncapsulationPrivateKey;\n\n private constructor(\n signingPrivateKey: SigningPrivateKey,\n encapsulationPrivateKey: EncapsulationPrivateKey,\n ) {\n this._signingPrivateKey = signingPrivateKey;\n this._encapsulationPrivateKey = encapsulationPrivateKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new PrivateKeys container with the given keys.\n */\n static withKeys(\n signingPrivateKey: SigningPrivateKey,\n encapsulationPrivateKey: EncapsulationPrivateKey,\n ): PrivateKeys {\n return new PrivateKeys(signingPrivateKey, encapsulationPrivateKey);\n }\n\n /**\n * Create a new PrivateKeys container with random Ed25519/X25519 keys.\n */\n static new(): PrivateKeys {\n const signingKey = SigningPrivateKey.random();\n const encapsulationKey = EncapsulationPrivateKey.random();\n return new PrivateKeys(signingKey, encapsulationKey);\n }\n\n /**\n * Generate a new PrivateKeys container with random Ed25519/X25519 keys.\n * This is an alias for new() for API compatibility.\n */\n static generate(): PrivateKeys {\n return PrivateKeys.new();\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the signing private key.\n */\n signingPrivateKey(): SigningPrivateKey {\n return this._signingPrivateKey;\n }\n\n /**\n * Returns the encapsulation private key.\n *\n * Note: Named to match Rust's API (which has a typo but we maintain compatibility)\n */\n encapsulationPrivateKey(): EncapsulationPrivateKey {\n return this._encapsulationPrivateKey;\n }\n\n /**\n * Derive the corresponding public keys.\n */\n publicKeys(): PublicKeys {\n const signingPublicKey = this._signingPrivateKey.publicKey();\n const encapsulationPublicKey = this._encapsulationPrivateKey.publicKey();\n return PublicKeys.new(signingPublicKey, encapsulationPublicKey);\n }\n\n // ============================================================================\n // Signer Interface\n // ============================================================================\n\n /**\n * Sign a message with optional signing options using the signing private key.\n */\n signWithOptions(message: Uint8Array, options?: SigningOptions): Signature {\n return this._signingPrivateKey.signWithOptions(message, options);\n }\n\n /**\n * Sign a message using the signing private key.\n */\n sign(message: Uint8Array): Signature {\n return this._signingPrivateKey.sign(message);\n }\n\n // ============================================================================\n // Decrypter Interface\n // ============================================================================\n\n /**\n * Decapsulate a shared secret from a ciphertext.\n *\n * This implements the Decrypter interface, allowing PrivateKeys to be used\n * in encryption contexts where a shared secret needs to be recovered.\n */\n decapsulateSharedSecret(ciphertext: EncapsulationCiphertext): SymmetricKey {\n return this._encapsulationPrivateKey.decapsulateSharedSecret(ciphertext);\n }\n\n // ============================================================================\n // ReferenceProvider Interface\n // ============================================================================\n\n /**\n * Returns a unique reference to this PrivateKeys instance.\n *\n * The reference is derived from the SHA-256 hash of the tagged CBOR\n * representation, providing a unique, content-addressable identifier.\n */\n reference(): Reference {\n const digest = Digest.fromImage(this.taggedCborData());\n return Reference.from(digest);\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another PrivateKeys.\n */\n equals(other: PrivateKeys): boolean {\n return (\n this._signingPrivateKey.equals(other._signingPrivateKey) &&\n this._encapsulationPrivateKey.equals(other._encapsulationPrivateKey)\n );\n }\n\n /**\n * Get string representation.\n *\n * Format matches Rust: `PrivateKeys(<short_reference>)`\n */\n toString(): string {\n return `PrivateKeys(${this.reference().shortReference(\"hex\")})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with PrivateKeys.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_PRIVATE_KEYS.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [<SigningPrivateKey>, <EncapsulationPrivateKey>]\n */\n untaggedCbor(): Cbor {\n return cbor([this._signingPrivateKey.taggedCbor(), this._encapsulationPrivateKey.taggedCbor()]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a PrivateKeys by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): PrivateKeys {\n const elements = expectArray(cborValue);\n\n if (elements.length !== 2) {\n throw new Error(`PrivateKeys must have 2 elements, got ${elements.length}`);\n }\n\n const signingPrivateKey = SigningPrivateKey.fromTaggedCbor(elements[0]);\n const encapsulationPrivateKey = EncapsulationPrivateKey.fromTaggedCbor(elements[1]);\n\n return new PrivateKeys(signingPrivateKey, encapsulationPrivateKey);\n }\n\n /**\n * Creates a PrivateKeys by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): PrivateKeys {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): PrivateKeys {\n // Create a dummy instance for accessing instance methods\n const dummy = PrivateKeys.new();\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): PrivateKeys {\n const cborValue = decodeCbor(data);\n return PrivateKeys.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): PrivateKeys {\n const cborValue = decodeCbor(data);\n const dummy = PrivateKeys.new();\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_PRIVATE_KEYS.name;\n if (name === undefined) {\n throw new Error(\"PRIVATE_KEYS tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a PrivateKeys from a UR.\n */\n static fromUR(ur: UR): PrivateKeys {\n if (ur.urTypeStr() !== TAG_PRIVATE_KEYS.name) {\n throw new Error(`Expected UR type ${TAG_PRIVATE_KEYS.name}, got ${ur.urTypeStr()}`);\n }\n const dummy = PrivateKeys.new();\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a PrivateKeys from a UR string.\n */\n static fromURString(urString: string): PrivateKeys {\n const ur = UR.fromURString(urString);\n return PrivateKeys.fromUR(ur);\n }\n}\n","/**\n * PrivateKeyBase - Root cryptographic material for deterministic key derivation\n *\n * PrivateKeyBase is a 32-byte value that serves as the root of cryptographic\n * material from which various keys can be deterministically derived.\n *\n * # CBOR Serialization\n *\n * PrivateKeyBase is serialized with tag 40016:\n * ```\n * #6.40016(h'<32-byte-key-material>')\n * ```\n *\n * # UR Serialization\n *\n * UR type: `crypto-prvkey-base`\n *\n * Ported from bc-components-rust/src/private_key_base.rs\n */\n\nimport { SecureRandomNumberGenerator, type RandomNumberGenerator } from \"@bcts/rand\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { PRIVATE_KEY_BASE as TAG_PRIVATE_KEY_BASE } from \"@bcts/tags\";\nimport { hkdfHmacSha256 } from \"@bcts/crypto\";\n\nimport { X25519PrivateKey } from \"./x25519/x25519-private-key.js\";\nimport { Ed25519PrivateKey } from \"./ed25519/ed25519-private-key.js\";\nimport { ECPrivateKey } from \"./ec-key/ec-private-key.js\";\nimport { SigningPrivateKey } from \"./signing/signing-private-key.js\";\nimport { EncapsulationPrivateKey } from \"./encapsulation/encapsulation-private-key.js\";\nimport { bytesToHex } from \"./utils.js\";\nimport { PrivateKeys } from \"./private-keys.js\";\nimport type { PublicKeys } from \"./public-keys.js\";\n\n/** Default size of PrivateKeyBase key material in bytes (used for random generation) */\nconst PRIVATE_KEY_BASE_DEFAULT_SIZE = 32;\n\n/** Key derivation salt string - must match Rust's bc-crypto derive functions */\nconst SALT_SIGNING = \"signing\";\n\n/**\n * PrivateKeyBase - Root cryptographic material for deterministic key derivation.\n *\n * This is the foundation from which signing keys and agreement keys can be\n * deterministically derived using HKDF.\n */\nexport class PrivateKeyBase\n implements CborTaggedEncodable, CborTaggedDecodable<PrivateKeyBase>, UREncodable\n{\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length === 0) {\n throw new Error(\"PrivateKeyBase must have non-zero length\");\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new random PrivateKeyBase.\n */\n static new(): PrivateKeyBase {\n const rng = new SecureRandomNumberGenerator();\n return PrivateKeyBase.newUsing(rng);\n }\n\n /**\n * Create a new random PrivateKeyBase using the provided RNG.\n */\n static newUsing(rng: RandomNumberGenerator): PrivateKeyBase {\n const data = rng.randomData(PRIVATE_KEY_BASE_DEFAULT_SIZE);\n return new PrivateKeyBase(data);\n }\n\n /**\n * Create a PrivateKeyBase from raw bytes.\n *\n * @param data - 32 bytes of key material\n */\n static fromData(data: Uint8Array): PrivateKeyBase {\n return new PrivateKeyBase(data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the raw key material.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw key material.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n // ============================================================================\n // Key Derivation Methods\n // ============================================================================\n\n /**\n * Derive an Ed25519 signing private key.\n *\n * Uses HKDF with salt \"signing\", matching Rust's derive_signing_private_key().\n */\n ed25519SigningPrivateKey(): SigningPrivateKey {\n const derivedKey = this._deriveKey(SALT_SIGNING);\n const ed25519Key = Ed25519PrivateKey.from(derivedKey);\n return SigningPrivateKey.newEd25519(ed25519Key);\n }\n\n /**\n * Derive an X25519 agreement private key.\n *\n * Uses HKDF with salt \"agreement\", matching Rust's derive_agreement_private_key().\n */\n x25519PrivateKey(): X25519PrivateKey {\n return X25519PrivateKey.deriveFromKeyMaterial(this._data);\n }\n\n /**\n * Get EncapsulationPrivateKey for decryption.\n *\n * Returns the derived X25519 private key wrapped as EncapsulationPrivateKey.\n */\n encapsulationPrivateKey(): EncapsulationPrivateKey {\n return EncapsulationPrivateKey.fromX25519PrivateKey(this.x25519PrivateKey());\n }\n\n /**\n * Derive a PrivateKeys container with Ed25519 signing and X25519 agreement keys.\n *\n * @returns PrivateKeys containing the derived signing and encapsulation keys\n */\n ed25519PrivateKeys(): PrivateKeys {\n return PrivateKeys.withKeys(this.ed25519SigningPrivateKey(), this.encapsulationPrivateKey());\n }\n\n /**\n * Derive a PublicKeys container from the derived keys.\n *\n * @returns PublicKeys containing the derived public keys\n */\n ed25519PublicKeys(): PublicKeys {\n const privateKeys = this.ed25519PrivateKeys();\n return privateKeys.publicKeys();\n }\n\n /**\n * Derive a Schnorr signing private key.\n *\n * Uses ECPrivateKey.deriveFromKeyMaterial() matching Rust's\n * PrivateKeyBase::schnorr_signing_private_key().\n */\n schnorrSigningPrivateKey(): SigningPrivateKey {\n const ecKey = ECPrivateKey.deriveFromKeyMaterial(this._data);\n return SigningPrivateKey.newSchnorr(ecKey);\n }\n\n /**\n * Derive a PrivateKeys container with Schnorr signing and X25519 agreement keys.\n *\n * Matches Rust's PrivateKeyBase::schnorr_private_keys().\n */\n schnorrPrivateKeys(): PrivateKeys {\n return PrivateKeys.withKeys(this.schnorrSigningPrivateKey(), this.encapsulationPrivateKey());\n }\n\n /**\n * Derive a PublicKeys container from Schnorr derived keys.\n */\n schnorrPublicKeys(): PublicKeys {\n return this.schnorrPrivateKeys().publicKeys();\n }\n\n /**\n * Derive an ECDSA signing private key.\n *\n * Uses ECPrivateKey.deriveFromKeyMaterial() matching Rust's\n * PrivateKeyBase::ecdsa_signing_private_key().\n */\n ecdsaSigningPrivateKey(): SigningPrivateKey {\n const ecKey = ECPrivateKey.deriveFromKeyMaterial(this._data);\n return SigningPrivateKey.newEcdsa(ecKey);\n }\n\n /**\n * Derive a PrivateKeys container with ECDSA signing and X25519 agreement keys.\n *\n * Matches Rust's PrivateKeyBase::ecdsa_private_keys().\n */\n ecdsaPrivateKeys(): PrivateKeys {\n return PrivateKeys.withKeys(this.ecdsaSigningPrivateKey(), this.encapsulationPrivateKey());\n }\n\n /**\n * Derive a PublicKeys container from ECDSA derived keys.\n */\n ecdsaPublicKeys(): PublicKeys {\n return this.ecdsaPrivateKeys().publicKeys();\n }\n\n /**\n * Internal key derivation using HKDF-SHA256.\n * Matches Rust's hkdf_hmac_sha256(key_material, salt, key_len) with empty info.\n */\n private _deriveKey(salt: string): Uint8Array {\n return hkdfHmacSha256(this._data, new TextEncoder().encode(salt), 32);\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another PrivateKeyBase.\n */\n equals(other: PrivateKeyBase): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation (truncated for security).\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `PrivateKeyBase(${hex.substring(0, 8)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with PrivateKeyBase.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_PRIVATE_KEY_BASE.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a PrivateKeyBase by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): PrivateKeyBase {\n const data = expectBytes(cborValue);\n return PrivateKeyBase.fromData(data);\n }\n\n /**\n * Creates a PrivateKeyBase by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): PrivateKeyBase {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): PrivateKeyBase {\n const dummy = new PrivateKeyBase(new Uint8Array(PRIVATE_KEY_BASE_DEFAULT_SIZE));\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): PrivateKeyBase {\n const cborValue = decodeCbor(data);\n return PrivateKeyBase.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): PrivateKeyBase {\n const cborValue = decodeCbor(data);\n const dummy = new PrivateKeyBase(new Uint8Array(PRIVATE_KEY_BASE_DEFAULT_SIZE));\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_PRIVATE_KEY_BASE.name;\n if (name === undefined) {\n throw new Error(\"PRIVATE_KEY_BASE tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a PrivateKeyBase from a UR.\n */\n static fromUR(ur: UR): PrivateKeyBase {\n if (ur.urTypeStr() !== TAG_PRIVATE_KEY_BASE.name) {\n throw new Error(`Expected UR type ${TAG_PRIVATE_KEY_BASE.name}, got ${ur.urTypeStr()}`);\n }\n const dummy = new PrivateKeyBase(new Uint8Array(PRIVATE_KEY_BASE_DEFAULT_SIZE));\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a PrivateKeyBase from a UR string.\n */\n static fromURString(urString: string): PrivateKeyBase {\n const ur = UR.fromURString(urString);\n return PrivateKeyBase.fromUR(ur);\n }\n}\n","/**\n * SSKR Integration - CBOR wrappers for SSKR shares\n *\n * This module provides CBOR serialization for SSKR (Sharded Secret Key\n * Reconstruction) shares. It wraps the core SSKR functionality from\n * @bcts/sskr with CBOR tags.\n *\n * # CBOR Serialization\n *\n * SSKRShare is serialized with tag 40309:\n * ```\n * #6.40309(h'<share-bytes>')\n * ```\n *\n * Legacy tag 309 is also supported for reading.\n *\n * Ported from bc-components-rust/src/sskr_mod.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n tagValue,\n} from \"@bcts/dcbor\";\nimport { SSKR_SHARE as TAG_SSKR_SHARE, SSKR_SHARE_V1 as TAG_SSKR_SHARE_V1 } from \"@bcts/tags\";\n\nimport { bytesToHex, hexToBytes } from \"./utils.js\";\nimport {\n sskrGenerate,\n sskrGenerateUsing,\n sskrCombine,\n Secret as SSKRSecret,\n GroupSpec as SSKRGroupSpec,\n Spec as SSKRSpec,\n} from \"@bcts/sskr\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\n\n// Re-export from sskr package\nexport { sskrGenerate, sskrGenerateUsing, sskrCombine, SSKRSecret, SSKRGroupSpec, SSKRSpec };\n\n/** Metadata size in bytes (identifier + thresholds + indices) */\nconst METADATA_SIZE_BYTES = 5;\n\n/**\n * SSKRShareCbor - CBOR/UR wrapper for an SSKR share.\n *\n * An SSKR share is a binary encoding of:\n * - Identifier (2 bytes)\n * - Group metadata (1 byte): group_threshold-1 (4 bits) + group_count-1 (4 bits)\n * - Member metadata (1 byte): group_index (4 bits) + member_threshold-1 (4 bits)\n * - Member index (1 byte): reserved (4 bits, must be 0) + member_index (4 bits)\n * - Share value (variable length)\n */\nexport class SSKRShareCbor implements CborTaggedEncodable, CborTaggedDecodable<SSKRShareCbor> {\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length < METADATA_SIZE_BYTES) {\n throw new Error(\n `SSKRShare must be at least ${METADATA_SIZE_BYTES} bytes, got ${data.length}`,\n );\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an SSKRShareCbor from raw share bytes.\n *\n * @param data - The share bytes (5+ bytes)\n */\n static fromData(data: Uint8Array): SSKRShareCbor {\n return new SSKRShareCbor(data);\n }\n\n /**\n * Create an SSKRShareCbor from a hex string.\n *\n * @param hex - The share as a hex string\n */\n static fromHex(hex: string): SSKRShareCbor {\n return new SSKRShareCbor(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods - Data Access\n // ============================================================================\n\n /**\n * Returns the raw share bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw share bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the share as a hex string.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n // ============================================================================\n // Instance Methods - Metadata Access\n // ============================================================================\n\n /**\n * Returns the identifier (2 bytes) as a number.\n */\n identifier(): number {\n return (this._data[0] << 8) | this._data[1];\n }\n\n /**\n * Returns the identifier as a hex string.\n */\n identifierHex(): string {\n return bytesToHex(this._data.subarray(0, 2));\n }\n\n /**\n * Returns the group threshold (minimum number of groups needed).\n */\n groupThreshold(): number {\n return (this._data[2] >> 4) + 1;\n }\n\n /**\n * Returns the total number of groups.\n */\n groupCount(): number {\n return (this._data[2] & 0x0f) + 1;\n }\n\n /**\n * Returns this share's group index (0-based).\n */\n groupIndex(): number {\n return this._data[3] >> 4;\n }\n\n /**\n * Returns the member threshold for this share's group.\n */\n memberThreshold(): number {\n return (this._data[3] & 0x0f) + 1;\n }\n\n /**\n * Returns this share's member index within its group (0-based).\n */\n memberIndex(): number {\n return this._data[4] & 0x0f;\n }\n\n /**\n * Returns the share value (the actual secret share data).\n */\n shareValue(): Uint8Array {\n return this._data.subarray(METADATA_SIZE_BYTES);\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another SSKRShareCbor.\n */\n equals(other: SSKRShareCbor): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `SSKRShare(${this.identifierHex()}, group ${this.groupIndex() + 1}/${this.groupCount()}, member ${this.memberIndex() + 1}/${this.memberThreshold()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with SSKRShare.\n * Includes both current tag (40309) and legacy tag (309) for compatibility.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SSKR_SHARE.value, TAG_SSKR_SHARE_V1.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an SSKRShareCbor by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): SSKRShareCbor {\n const data = expectBytes(cborValue);\n return SSKRShareCbor.fromData(data);\n }\n\n /**\n * Creates an SSKRShareCbor by decoding it from tagged CBOR.\n * Accepts both tag 40309 and legacy tag 309.\n */\n fromTaggedCbor(cborValue: Cbor): SSKRShareCbor {\n const tag = tagValue(cborValue);\n\n // Accept both current and legacy tags\n if (tag !== TAG_SSKR_SHARE.value && tag !== TAG_SSKR_SHARE_V1.value) {\n throw new Error(\n `Invalid SSKRShare tag: expected ${TAG_SSKR_SHARE.value} or ${TAG_SSKR_SHARE_V1.value}, got ${tag}`,\n );\n }\n\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): SSKRShareCbor {\n const dummy = new SSKRShareCbor(new Uint8Array(METADATA_SIZE_BYTES + 16));\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): SSKRShareCbor {\n const cborValue = decodeCbor(data);\n return SSKRShareCbor.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): SSKRShareCbor {\n const cborValue = decodeCbor(data);\n const dummy = new SSKRShareCbor(new Uint8Array(METADATA_SIZE_BYTES + 16));\n return dummy.fromUntaggedCbor(cborValue);\n }\n}\n\n// ============================================================================\n// Type Alias for Rust Parity\n// ============================================================================\n\n/**\n * SSKRShare - Alias for SSKRShareCbor to match Rust API naming.\n *\n * In Rust, this type is called `SSKRShare`. The TypeScript implementation\n * uses `SSKRShareCbor` to distinguish it from raw share data, but we provide\n * this alias for API parity with bc-components-rust.\n */\nexport type SSKRShare = SSKRShareCbor;\n\n/**\n * Create an SSKRShare from raw data.\n * This is a convenience function that matches the Rust constructor pattern.\n */\n// eslint-disable-next-line no-redeclare -- Intentional: TypeScript allows type/value with same name\nexport const SSKRShare = {\n fromData: (data: Uint8Array): SSKRShareCbor => SSKRShareCbor.fromData(data),\n fromHex: (hex: string): SSKRShareCbor => SSKRShareCbor.fromHex(hex),\n fromTaggedCbor: (cborValue: Cbor): SSKRShareCbor => SSKRShareCbor.fromTaggedCbor(cborValue),\n fromTaggedCborData: (data: Uint8Array): SSKRShareCbor => SSKRShareCbor.fromTaggedCborData(data),\n fromUntaggedCborData: (data: Uint8Array): SSKRShareCbor =>\n SSKRShareCbor.fromUntaggedCborData(data),\n};\n\n// ============================================================================\n// Wrapper Functions (Rust API Parity)\n// ============================================================================\n\n/**\n * Generates SSKR shares for the given spec and secret.\n *\n * This function matches the Rust `sskr_generate` API by returning wrapped\n * SSKRShare objects instead of raw byte arrays.\n *\n * @param spec - The SSKRSpec instance defining group/member thresholds\n * @param masterSecret - The SSKRSecret to be split into shares\n * @returns Nested array of SSKRShare instances (groups × members)\n *\n * @example\n * ```typescript\n * import { SSKRSecret, SSKRSpec, SSKRGroupSpec, sskrGenerateShares } from '@bcts/components';\n *\n * const secret = SSKRSecret.new(new Uint8Array(16).fill(0x42));\n * const group = SSKRGroupSpec.new(2, 3); // 2 of 3\n * const spec = SSKRSpec.new(1, [group]); // 1 group required\n *\n * const shares = sskrGenerateShares(spec, secret);\n * // shares[0] contains 3 SSKRShare instances\n * ```\n */\nexport function sskrGenerateShares(spec: SSKRSpec, masterSecret: SSKRSecret): SSKRShare[][] {\n const rawGroups = sskrGenerate(spec, masterSecret);\n return rawGroups.map((group) => group.map((shareData) => SSKRShareCbor.fromData(shareData)));\n}\n\n/**\n * Interface for RNG that only requires fillRandomData method.\n * This is a subset of the full RandomNumberGenerator interface.\n */\nexport interface SimpleRng {\n fillRandomData(data: Uint8Array): void;\n}\n\n/**\n * Generates SSKR shares using a custom random number generator.\n *\n * This function matches the Rust `sskr_generate_using` API by returning\n * wrapped SSKRShare objects and allowing a custom RNG for deterministic\n * testing.\n *\n * @param spec - The SSKRSpec instance defining group/member thresholds\n * @param masterSecret - The SSKRSecret to be split into shares\n * @param rng - Random number generator (must have fillRandomData method)\n * @returns Nested array of SSKRShare instances (groups × members)\n */\nexport function sskrGenerateSharesUsing(\n spec: SSKRSpec,\n masterSecret: SSKRSecret,\n rng: SimpleRng,\n): SSKRShare[][] {\n // Cast to RandomNumberGenerator - sskrGenerateUsing only uses fillRandomData internally\n const rawGroups = sskrGenerateUsing(spec, masterSecret, rng as unknown as RandomNumberGenerator);\n return rawGroups.map((group) => group.map((shareData) => SSKRShareCbor.fromData(shareData)));\n}\n\n/**\n * Combines SSKR shares to reconstruct the original secret.\n *\n * This function matches the Rust `sskr_combine` API by accepting\n * wrapped SSKRShare objects.\n *\n * @param shares - Array of SSKRShare instances to combine\n * @returns The reconstructed SSKRSecret\n * @throws Error if shares cannot be combined (insufficient shares, mismatched IDs, etc.)\n *\n * @example\n * ```typescript\n * import { sskrGenerateShares, sskrCombineShares } from '@bcts/components';\n *\n * // Generate shares\n * const shares = sskrGenerateShares(spec, secret);\n *\n * // Combine 2 shares from the first group\n * const recoveredSecret = sskrCombineShares([shares[0][0], shares[0][1]]);\n * ```\n */\nexport function sskrCombineShares(shares: SSKRShare[]): SSKRSecret {\n const rawShares = shares.map((share) => share.data());\n return sskrCombine(rawShares);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;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,IAAI,WAAW,sBAAsB,GAAG,CAAC,CAC5D,iBAAiB,UAAU;;;;;;;AAsB5C,MAAa,YAAY;CACvB,WAAW,SAAoC,cAAc,SAAS,KAAK;CAC3E,UAAU,QAA+B,cAAc,QAAQ,IAAI;CACnE,iBAAiB,cAAmC,cAAc,eAAe,UAAU;CAC3F,qBAAqB,SAAoC,cAAc,mBAAmB,KAAK;CAC/F,uBAAuB,SACrB,cAAc,qBAAqB,KAAK;CAC3C;;;;;;;;;;;;;;;;;;;;;;;AA4BD,SAAgB,mBAAmB,MAAgB,cAAyC;AAE1F,qCAD+B,MAAM,aAAa,CACjC,KAAK,UAAU,MAAM,KAAK,cAAc,cAAc,SAAS,UAAU,CAAC,CAAC;;;;;;;;;;;;;;AAuB9F,SAAgB,wBACd,MACA,cACA,KACe;AAGf,0CADoC,MAAM,cAAc,IAAwC,CAC/E,KAAK,UAAU,MAAM,KAAK,cAAc,cAAc,SAAS,UAAU,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;AAwB9F,SAAgB,kBAAkB,QAAiC;AAEjE,oCADkB,OAAO,KAAK,UAAU,MAAM,MAAM,CAAC,CACxB"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["hexToBytes","bytesToHex","TAG_JSON","CryptoError","bytesToHex","TAG_COMPRESSED","Digest","Digest","SYMMETRIC_NONCE_SIZE","CryptoError","SecureRandomNumberGenerator","hexToBytes","bytesToHex","toBase64","TAG_NONCE","cbor","UR","hexToBytes","SecureRandomNumberGenerator","CryptoError","bytesToHex","toBase64","TAG_SALT","cbor","UR","CryptoError","SecureRandomNumberGenerator","hexToBytes","bytesToHex","toBase64","TAG_SEED","TAG_SEED_V1","CborMap","CborDate","cbor","UR","Digest","CryptoError","CryptoError","SecureRandomNumberGenerator","hexToBytes","bytesToHex","toBase64","TAG_ARID","cbor","UR","CryptoError","bytesToHex","toBase64","TAG_UUID","cbor","UR","CryptoError","Digest","bytesToHex","toBase64","TAG_XID","cbor","UR","CryptoError","toBase64","TAG_URI","UR","X25519_PUBLIC_KEY_SIZE","CryptoError","hexToBytes","bytesToHex","toBase64","TAG_X25519_PUBLIC_KEY","cbor","UR","CryptoError","hexToBytes","bytesToHex","toBase64","cbor","Digest","bytesToHex","TAG_ENCRYPTED","UR","CryptoError","hexToBytes","SecureRandomNumberGenerator","bytesToHex","toBase64","TAG_SYMMETRIC_KEY","cbor","UR","X25519_PRIVATE_KEY_SIZE","CryptoError","SecureRandomNumberGenerator","hexToBytes","bytesToHex","toBase64","TAG_X25519_PRIVATE_KEY","cbor","UR","ED25519_PUBLIC_KEY_SIZE","CryptoError","hexToBytes","bytesToHex","toBase64","ED25519_SIGNATURE_SIZE","ED25519_PRIVATE_KEY_SIZE","CryptoError","hexToBytes","SecureRandomNumberGenerator","bytesToHex","toBase64","bytesToHex","sr25519","SecureRandomNumberGenerator","bytesToHex","sr25519","ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE","CryptoError","hexToBytes","bytesToHex","toBase64","TAG_EC_KEY","TAG_EC_KEY_V1","UR","ECDSA_PUBLIC_KEY_SIZE","CryptoError","hexToBytes","bytesToHex","toBase64","TAG_EC_KEY","TAG_EC_KEY_V1","UR","SCHNORR_PUBLIC_KEY_SIZE","CryptoError","hexToBytes","bytesToHex","toBase64","ECDSA_PRIVATE_KEY_SIZE","CryptoError","SecureRandomNumberGenerator","hexToBytes","bytesToHex","toBase64","TAG_EC_KEY","TAG_EC_KEY_V1","UR","SecureRandomNumberGenerator","ml_dsa44","ml_dsa65","ml_dsa87","bytesToHex","TAG_MLDSA_PUBLIC_KEY","UR","bytesToHex","TAG_MLDSA_SIGNATURE","UR","SecureRandomNumberGenerator","bytesToHex","TAG_MLDSA_PRIVATE_KEY","UR","SCHNORR_SIGNATURE_SIZE","CryptoError","hexToBytes","ECDSA_SIGNATURE_SIZE","ED25519_SIGNATURE_SIZE","bytesToHex","TAG_SIGNATURE","TAG_MLDSA_SIGNATURE","UR","Digest","TAG_SIGNING_PUBLIC_KEY","TAG_MLDSA_PUBLIC_KEY","ED25519_PUBLIC_KEY_SIZE","UR","Digest","sigData","TAG_SIGNING_PRIVATE_KEY","TAG_MLDSA_PRIVATE_KEY","ED25519_PRIVATE_KEY_SIZE","UR","CryptoError","SecureRandomNumberGenerator","ml_kem512","ml_kem768","ml_kem1024","bytesToHex","TAG_MLKEM_CIPHERTEXT","UR","mlkemLevelToScheme","isMlkemScheme","bytesToHex","TAG_X25519_PUBLIC_KEY","TAG_MLKEM_CIPHERTEXT","bytesToHex","TAG_MLKEM_PUBLIC_KEY","UR","mlkemLevelToScheme","isMlkemScheme","bytesToHex","Digest","TAG_X25519_PUBLIC_KEY","TAG_MLKEM_PUBLIC_KEY","UR","SecureRandomNumberGenerator","bytesToHex","TAG_MLKEM_PRIVATE_KEY","UR","SecureRandomNumberGenerator","CryptoError","bytesToHex","Digest","TAG_X25519_PRIVATE_KEY","TAG_MLKEM_PRIVATE_KEY","UR","bytesToHex","TAG_SEALED_MESSAGE","UR","SALT_LEN","CryptoError","CryptoError","TAG_ENCRYPTED_KEY","UR","Digest","TAG_PUBLIC_KEYS","UR","Digest","TAG_PRIVATE_KEYS","UR","SecureRandomNumberGenerator","bytesToHex","TAG_PRIVATE_KEY_BASE","UR","hexToBytes","bytesToHex","TAG_SSKR_SHARE","TAG_SSKR_SHARE_V1"],"sources":["../src/private-key-data-provider.ts","../src/encrypter.ts","../src/json.ts","../src/compressed.ts","../src/hkdf-rng.ts","../src/digest-provider.ts","../src/nonce.ts","../src/salt.ts","../src/seed.ts","../src/reference.ts","../src/id/arid.ts","../src/id/uuid.ts","../src/id/xid.ts","../src/id/uri.ts","../src/x25519/x25519-public-key.ts","../src/symmetric/authentication-tag.ts","../src/symmetric/encrypted-message.ts","../src/symmetric/symmetric-key.ts","../src/x25519/x25519-private-key.ts","../src/ed25519/ed25519-public-key.ts","../src/ed25519/ed25519-private-key.ts","../src/sr25519/sr25519-public-key.ts","../src/sr25519/sr25519-private-key.ts","../src/ec-key/ec-key-base.ts","../src/ec-key/ec-uncompressed-public-key.ts","../src/ec-key/ec-public-key.ts","../src/ec-key/schnorr-public-key.ts","../src/ec-key/ec-private-key.ts","../src/mldsa/mldsa-level.ts","../src/mldsa/mldsa-public-key.ts","../src/mldsa/mldsa-signature.ts","../src/mldsa/mldsa-private-key.ts","../src/signing/signature.ts","../src/signing/signing-public-key.ts","../src/signing/signing-private-key.ts","../src/signing/signature-scheme.ts","../src/mlkem/mlkem-level.ts","../src/mlkem/mlkem-ciphertext.ts","../src/encapsulation/encapsulation-ciphertext.ts","../src/mlkem/mlkem-public-key.ts","../src/encapsulation/encapsulation-public-key.ts","../src/mlkem/mlkem-private-key.ts","../src/encapsulation/encapsulation-private-key.ts","../src/encapsulation/encapsulation-scheme.ts","../src/encapsulation/sealed-message.ts","../src/encrypted-key/hash-type.ts","../src/encrypted-key/key-derivation-method.ts","../src/encrypted-key/hkdf-params.ts","../src/encrypted-key/pbkdf2-params.ts","../src/encrypted-key/scrypt-params.ts","../src/encrypted-key/argon2id-params.ts","../src/encrypted-key/ssh-agent-params.ts","../src/encrypted-key/key-derivation-params.ts","../src/encrypted-key/encrypted-key.ts","../src/public-keys.ts","../src/private-keys.ts","../src/private-key-base.ts","../src/sskr.ts"],"sourcesContent":["/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * A trait for types that can provide unique data for cryptographic key derivation.\n *\n * Ported from bc-components-rust/src/private_key_data_provider.rs\n *\n * Types implementing `PrivateKeyDataProvider` can be used as seed material for\n * cryptographic key derivation. The provided data should be sufficiently\n * random and unpredictable to ensure the security of the derived keys.\n *\n * This trait is particularly useful for:\n * - Deterministic key generation systems\n * - Key recovery mechanisms\n * - Key derivation hierarchies\n * - Hierarchical deterministic wallet implementations\n *\n * # Security Considerations\n *\n * Implementers of this trait should ensure that:\n * - The data they provide has sufficient entropy\n * - The data is properly protected in memory\n * - Any serialization or storage is done securely\n * - Appropriate zeroization occurs when data is no longer needed\n */\n\n/**\n * Interface for types that can provide unique data for cryptographic key derivation.\n *\n * The provided data should be sufficiently random and have enough entropy\n * to serve as the basis for secure cryptographic key derivation.\n */\nexport interface PrivateKeyDataProvider {\n /**\n * Returns unique data from which cryptographic keys can be derived.\n *\n * The returned data should be sufficiently random and have enough entropy\n * to serve as the basis for secure cryptographic key derivation.\n *\n * @returns A Uint8Array containing the private key data.\n */\n privateKeyData(): Uint8Array;\n}\n\n/**\n * Type guard to check if an object implements PrivateKeyDataProvider\n */\nexport function isPrivateKeyDataProvider(obj: unknown): obj is PrivateKeyDataProvider {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"privateKeyData\" in obj &&\n typeof (obj as PrivateKeyDataProvider).privateKeyData === \"function\"\n );\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Encrypter and Decrypter interfaces for public key encryption/decryption.\n *\n * Ported from bc-components-rust/src/encrypter.rs\n *\n * The `Encrypter` interface defines an interface for encapsulating a shared secret\n * using a public key. This is a key part of hybrid encryption schemes, where a\n * shared symmetric key is encapsulated with a public key, and the recipient\n * uses their private key to recover the symmetric key.\n *\n * The `Decrypter` interface defines an interface for decapsulating (recovering) a\n * shared secret using a private key. This is the counterpart to the\n * `Encrypter` interface and is used by the recipient of encapsulated messages.\n */\n\nimport type { EncapsulationCiphertext } from \"./encapsulation/encapsulation-ciphertext.js\";\nimport type { EncapsulationPrivateKey } from \"./encapsulation/encapsulation-private-key.js\";\nimport type { EncapsulationPublicKey } from \"./encapsulation/encapsulation-public-key.js\";\nimport type { SymmetricKey } from \"./symmetric/symmetric-key.js\";\n\n/**\n * A trait for types that can encapsulate shared secrets for public key encryption.\n *\n * The `Encrypter` interface defines an interface for encapsulating a shared secret\n * using a public key. This is a key part of hybrid encryption schemes, where a\n * shared symmetric key is encapsulated with a public key, and the recipient\n * uses their private key to recover the symmetric key.\n *\n * Types implementing this interface provide the ability to:\n * 1. Access their encapsulation public key\n * 2. Generate and encapsulate new shared secrets\n *\n * This interface is typically implemented by:\n * - Encapsulation public keys\n * - Higher-level types that contain or can generate encapsulation public keys\n *\n * @example\n * ```typescript\n * import { EncapsulationScheme, createEncapsulationKeypair } from '@bcts/components';\n *\n * // Generate a recipient keypair\n * const [recipientPrivateKey, recipientPublicKey] = createEncapsulationKeypair(EncapsulationScheme.X25519);\n *\n * // Encapsulate a new shared secret\n * const [sharedSecret, ciphertext] = recipientPublicKey.encapsulateNewSharedSecret();\n * ```\n */\nexport interface Encrypter {\n /**\n * Returns the encapsulation public key for this encrypter.\n *\n * @returns The encapsulation public key that should be used for encapsulation.\n */\n encapsulationPublicKey(): EncapsulationPublicKey;\n\n /**\n * Encapsulates a new shared secret for the recipient.\n *\n * This method generates a new shared secret and encapsulates it using\n * the encapsulation public key from this encrypter.\n *\n * @returns A tuple containing:\n * - The generated shared secret as a `SymmetricKey`\n * - The encapsulation ciphertext that can be sent to the recipient\n */\n encapsulateNewSharedSecret(): [SymmetricKey, EncapsulationCiphertext];\n}\n\n/**\n * A trait for types that can decapsulate shared secrets for public key decryption.\n *\n * The `Decrypter` interface defines an interface for decapsulating (recovering) a\n * shared secret using a private key. This is the counterpart to the\n * `Encrypter` interface and is used by the recipient of encapsulated messages.\n *\n * Types implementing this interface provide the ability to:\n * 1. Access their encapsulation private key\n * 2. Decapsulate shared secrets from ciphertexts\n *\n * This interface is typically implemented by:\n * - Encapsulation private keys\n * - Higher-level types that contain or can access encapsulation private keys\n *\n * @example\n * ```typescript\n * import { EncapsulationScheme, createEncapsulationKeypair } from '@bcts/components';\n *\n * // Generate a keypair\n * const [privateKey, publicKey] = createEncapsulationKeypair(EncapsulationScheme.X25519);\n *\n * // Encapsulate a new shared secret\n * const [originalSecret, ciphertext] = publicKey.encapsulateNewSharedSecret();\n *\n * // Decapsulate the shared secret\n * const recoveredSecret = privateKey.decapsulateSharedSecret(ciphertext);\n *\n * // The original and recovered secrets should match\n * ```\n */\nexport interface Decrypter {\n /**\n * Returns the encapsulation private key for this decrypter.\n *\n * @returns The encapsulation private key that should be used for decapsulation.\n */\n encapsulationPrivateKey(): EncapsulationPrivateKey;\n\n /**\n * Decapsulates a shared secret from a ciphertext.\n *\n * This method recovers the shared secret that was encapsulated in the\n * given ciphertext, using the private key from this decrypter.\n *\n * @param ciphertext - The encapsulation ciphertext containing the encapsulated shared secret\n * @returns The decapsulated `SymmetricKey`\n * @throws Error if the ciphertext type doesn't match the private key type or if decapsulation fails\n */\n decapsulateSharedSecret(ciphertext: EncapsulationCiphertext): SymmetricKey;\n}\n\n/**\n * Type guard to check if an object implements the Encrypter interface.\n */\nexport function isEncrypter(obj: unknown): obj is Encrypter {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"encapsulationPublicKey\" in obj &&\n typeof (obj as Encrypter).encapsulationPublicKey === \"function\" &&\n \"encapsulateNewSharedSecret\" in obj &&\n typeof (obj as Encrypter).encapsulateNewSharedSecret === \"function\"\n );\n}\n\n/**\n * Type guard to check if an object implements the Decrypter interface.\n */\nexport function isDecrypter(obj: unknown): obj is Decrypter {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"encapsulationPrivateKey\" in obj &&\n typeof (obj as Decrypter).encapsulationPrivateKey === \"function\" &&\n \"decapsulateSharedSecret\" in obj &&\n typeof (obj as Decrypter).decapsulateSharedSecret === \"function\"\n );\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * A CBOR-tagged container for UTF-8 JSON text.\n *\n * Ported from bc-components-rust/src/json.rs\n *\n * The `JSON` type wraps UTF-8 JSON text as a CBOR byte string with tag 262.\n * This allows JSON data to be embedded within CBOR structures while\n * maintaining type information through the tag.\n *\n * This implementation does not validate that the contained data is well-formed\n * JSON. It simply provides a type-safe wrapper around byte data that is\n * intended to contain JSON text.\n *\n * # CBOR Serialization\n *\n * `JSON` implements the CBOR tagged encoding interfaces, which means it can be\n * serialized to and deserialized from CBOR with tag 262 (`TAG_JSON`).\n *\n * @example\n * ```typescript\n * import { JSON } from '@bcts/components';\n *\n * // Create JSON from a string\n * const json = JSON.fromString('{\"key\": \"value\"}');\n * console.log(json.asStr()); // {\"key\": \"value\"}\n *\n * // Create JSON from bytes\n * const json2 = JSON.fromData(new TextEncoder().encode('[1, 2, 3]'));\n * console.log(json2.len()); // 9\n * ```\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { JSON as TAG_JSON } from \"@bcts/tags\";\nimport { bytesToHex, hexToBytes } from \"./utils.js\";\n\n/**\n * A CBOR-tagged container for UTF-8 JSON text.\n *\n * Wraps UTF-8 JSON text as a CBOR byte string with tag 262.\n * This allows JSON data to be embedded within CBOR structures while\n * maintaining type information through the tag.\n */\nexport class JSON implements CborTaggedEncodable, CborTaggedDecodable<JSON> {\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new JSON instance from byte data.\n */\n static fromData(data: Uint8Array): JSON {\n return new JSON(data);\n }\n\n /**\n * Create a new JSON instance from a string.\n */\n static fromString(s: string): JSON {\n const encoder = new TextEncoder();\n return new JSON(encoder.encode(s));\n }\n\n /**\n * Create a new JSON instance from a hexadecimal string.\n */\n static fromHex(hex: string): JSON {\n return new JSON(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Return the length of the JSON data in bytes.\n */\n len(): number {\n return this._data.length;\n }\n\n /**\n * Return true if the JSON data is empty.\n */\n isEmpty(): boolean {\n return this._data.length === 0;\n }\n\n /**\n * Return the data as a byte slice.\n */\n asBytes(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Return the data as a UTF-8 string slice.\n *\n * @throws Error if the data is not valid UTF-8.\n */\n asStr(): string {\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n return decoder.decode(this._data);\n }\n\n /**\n * Return the data as a hexadecimal string.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Return a copy of the underlying data.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Compare with another JSON.\n */\n equals(other: JSON): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `JSON(${this.asStr()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with JSON.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_JSON.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a JSON by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): JSON {\n const data = expectBytes(cborValue);\n return JSON.fromData(data);\n }\n\n /**\n * Creates a JSON by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): JSON {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): JSON {\n const instance = JSON.fromString(\"\");\n return instance.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): JSON {\n const cborValue = decodeCbor(data);\n return JSON.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): JSON {\n const cborValue = decodeCbor(data);\n const instance = JSON.fromString(\"\");\n return instance.fromUntaggedCbor(cborValue);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * A compressed binary object with integrity verification.\n *\n * Ported from bc-components-rust/src/compressed.rs\n *\n * `Compressed` provides a way to efficiently store and transmit binary data\n * using the DEFLATE compression algorithm. It includes built-in integrity\n * verification through a CRC32 checksum and optional cryptographic digest.\n *\n * The compression is implemented using the raw DEFLATE format as described in\n * [IETF RFC 1951](https://www.ietf.org/rfc/rfc1951.txt).\n *\n * Features:\n * - Automatic compression with configurable compression level\n * - Integrity verification via CRC32 checksum\n * - Optional cryptographic digest for content identification\n * - Smart behavior for small data (stores decompressed if compression would\n * increase size)\n * - CBOR serialization/deserialization support\n *\n * @example\n * ```typescript\n * import { Compressed } from '@bcts/components';\n *\n * // Compress a string\n * const data = new TextEncoder().encode(\n * \"This is a longer string that should compress well with repeated patterns.\"\n * );\n * const compressed = Compressed.fromDecompressedData(data);\n *\n * // The compressed size should be smaller than the original\n * console.log(compressed.compressionRatio()); // < 1.0\n *\n * // We can recover the original data\n * const decompressed = compressed.decompress();\n * ```\n */\n\nimport { deflate, inflate } from \"pako\";\nimport { crc32 } from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborInput,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n expectArray,\n expectInteger,\n expectBytes,\n} from \"@bcts/dcbor\";\nimport { COMPRESSED as TAG_COMPRESSED } from \"@bcts/tags\";\nimport { Digest } from \"./digest.js\";\nimport type { DigestProvider } from \"./digest-provider.js\";\nimport { CryptoError } from \"./error.js\";\nimport { bytesToHex } from \"./utils.js\";\n\n/**\n * A compressed binary object with integrity verification.\n *\n * Uses DEFLATE compression with CRC32 checksums for integrity verification.\n * Optionally includes a cryptographic digest for content identification.\n */\nexport class Compressed\n implements CborTaggedEncodable, CborTaggedDecodable<Compressed>, DigestProvider\n{\n /** CRC32 checksum of the decompressed data for integrity verification */\n private readonly _checksum: number;\n /** Size of the original decompressed data in bytes */\n private readonly _decompressedSize: number;\n /** The compressed data (or original data if compression is ineffective) */\n private readonly _compressedData: Uint8Array;\n /** Optional cryptographic digest of the content */\n private readonly _digest: Digest | undefined;\n\n private constructor(\n checksum: number,\n decompressedSize: number,\n compressedData: Uint8Array,\n digest?: Digest,\n ) {\n if (compressedData.length > decompressedSize) {\n throw CryptoError.cryptoOperation(\"compressed data is larger than decompressed size\");\n }\n this._checksum = checksum;\n this._decompressedSize = decompressedSize;\n this._compressedData = new Uint8Array(compressedData);\n this._digest = digest;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Creates a new `Compressed` object with the specified parameters.\n *\n * This is a low-level constructor that allows direct creation of a\n * `Compressed` object without performing compression. It's primarily\n * intended for deserialization or when working with pre-compressed data.\n *\n * @param checksum - CRC32 checksum of the decompressed data\n * @param decompressedSize - Size of the original decompressed data in bytes\n * @param compressedData - The compressed data bytes\n * @param digest - Optional cryptographic digest of the content\n * @returns A new `Compressed` object\n * @throws CryptoError if the compressed data is larger than the decompressed size\n */\n static new(\n checksum: number,\n decompressedSize: number,\n compressedData: Uint8Array,\n digest?: Digest,\n ): Compressed {\n return new Compressed(checksum, decompressedSize, compressedData, digest);\n }\n\n /**\n * Creates a new `Compressed` object by compressing the provided data.\n *\n * This is the primary method for creating compressed data. It automatically\n * handles compression using the DEFLATE algorithm with compression level 6.\n *\n * If the compressed data would be larger than the original data (which can\n * happen with small or already compressed inputs), the original data is\n * stored instead.\n *\n * @param decompressedData - The original data to compress\n * @param digest - Optional cryptographic digest of the content\n * @returns A new `Compressed` object containing the compressed (or original) data\n */\n static fromDecompressedData(decompressedData: Uint8Array, digest?: Digest): Compressed {\n // Use raw DEFLATE compression (level 6 is default)\n const compressedData = deflate(decompressedData, { level: 6 });\n const checksum = crc32(decompressedData);\n const decompressedSize = decompressedData.length;\n const compressedSize = compressedData.length;\n\n // If compression didn't help, store original data\n if (compressedSize !== 0 && compressedSize < decompressedSize) {\n return new Compressed(checksum, decompressedSize, compressedData, digest);\n } else {\n return new Compressed(checksum, decompressedSize, new Uint8Array(decompressedData), digest);\n }\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Decompresses and returns the original decompressed data.\n *\n * This method performs the reverse of the compression process, restoring\n * the original data. It also verifies the integrity of the data using the\n * stored checksum.\n *\n * @returns The decompressed data\n * @throws CryptoError if the compressed data is corrupt or checksum doesn't match\n */\n decompress(): Uint8Array {\n const compressedSize = this._compressedData.length;\n\n // If data wasn't actually compressed (sizes equal), return as-is\n if (compressedSize >= this._decompressedSize) {\n return new Uint8Array(this._compressedData);\n }\n\n try {\n const decompressedData = inflate(this._compressedData);\n\n // Verify checksum\n if (crc32(decompressedData) !== this._checksum) {\n throw CryptoError.cryptoOperation(\"compressed data checksum mismatch\");\n }\n\n return decompressedData;\n } catch (e) {\n if (e instanceof CryptoError) throw e;\n throw CryptoError.cryptoOperation(\"corrupt compressed data\");\n }\n }\n\n /**\n * Returns the size of the compressed data in bytes.\n */\n compressedSize(): number {\n return this._compressedData.length;\n }\n\n /**\n * Returns the size of the decompressed data in bytes.\n */\n decompressedSize(): number {\n return this._decompressedSize;\n }\n\n /**\n * Returns the CRC32 checksum of the decompressed data.\n */\n checksum(): number {\n return this._checksum;\n }\n\n /**\n * Returns the compression ratio of the data.\n *\n * The compression ratio is calculated as (compressed size) / (decompressed size),\n * so lower values indicate better compression.\n *\n * @returns A floating-point value representing the compression ratio.\n * - Values less than 1.0 indicate effective compression\n * - Values equal to 1.0 indicate no compression was applied\n * - Values of NaN can occur if the decompressed size is zero\n */\n compressionRatio(): number {\n return this._compressedData.length / this._decompressedSize;\n }\n\n /**\n * Returns the digest of the compressed data, if available.\n *\n * @returns The `Digest` associated with this compressed data, or undefined if none.\n */\n digestOpt(): Digest | undefined {\n return this._digest;\n }\n\n /**\n * Returns whether this compressed data has an associated digest.\n */\n hasDigest(): boolean {\n return this._digest !== undefined;\n }\n\n // ============================================================================\n // DigestProvider implementation\n // ============================================================================\n\n /**\n * Returns the cryptographic digest associated with this compressed data.\n *\n * @returns A `Digest`\n * @throws Error if there is no digest associated with this compressed data\n */\n digest(): Digest {\n if (this._digest === undefined) {\n throw new Error(\"No digest associated with this compressed data\");\n }\n return this._digest;\n }\n\n // ============================================================================\n // Comparison and String representation\n // ============================================================================\n\n /**\n * Compare with another Compressed.\n */\n equals(other: Compressed): boolean {\n if (this._checksum !== other._checksum) return false;\n if (this._decompressedSize !== other._decompressedSize) return false;\n if (this._compressedData.length !== other._compressedData.length) return false;\n for (let i = 0; i < this._compressedData.length; i++) {\n if (this._compressedData[i] !== other._compressedData[i]) return false;\n }\n // Don't compare digests for equality\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n const checksumHex = bytesToHex(\n new Uint8Array([\n (this._checksum >>> 24) & 0xff,\n (this._checksum >>> 16) & 0xff,\n (this._checksum >>> 8) & 0xff,\n this._checksum & 0xff,\n ]),\n );\n const digestStr = this._digest?.shortDescription() ?? \"None\";\n return `Compressed(checksum: ${checksumHex}, size: ${this.compressedSize()}/${this._decompressedSize}, ratio: ${this.compressionRatio().toFixed(2)}, digest: ${digestStr})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with Compressed.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_COMPRESSED.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as an array).\n *\n * Format:\n * ```\n * [\n * checksum: uint,\n * decompressed_size: uint,\n * compressed_data: bytes,\n * digest?: Digest // Optional\n * ]\n * ```\n */\n untaggedCbor(): Cbor {\n const elements: CborInput[] = [\n this._checksum >>> 0, // Ensure unsigned 32-bit\n this._decompressedSize,\n toByteString(this._compressedData),\n ];\n if (this._digest !== undefined) {\n elements.push(this._digest.taggedCbor());\n }\n return cbor(elements);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a Compressed by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): Compressed {\n const elements = expectArray(cborValue);\n if (elements.length < 3 || elements.length > 4) {\n throw CryptoError.invalidData(\"invalid number of elements in compressed\");\n }\n\n const checksum = expectInteger(elements[0]);\n const decompressedSize = expectInteger(elements[1]);\n const compressedData = expectBytes(elements[2]);\n\n let digest: Digest | undefined;\n if (elements.length === 4) {\n digest = Digest.fromTaggedCbor(elements[3]);\n }\n\n return Compressed.new(Number(checksum), Number(decompressedSize), compressedData, digest);\n }\n\n /**\n * Creates a Compressed by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): Compressed {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): Compressed {\n const instance = Compressed.fromDecompressedData(new Uint8Array(0));\n return instance.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): Compressed {\n const cborValue = decodeCbor(data);\n return Compressed.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): Compressed {\n const cborValue = decodeCbor(data);\n const instance = Compressed.fromDecompressedData(new Uint8Array(0));\n return instance.fromUntaggedCbor(cborValue);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * A deterministic random number generator based on HKDF-HMAC-SHA256.\n *\n * Ported from bc-components-rust/src/hkdf_rng.rs\n *\n * `HKDFRng` uses the HMAC-based Key Derivation Function (HKDF) to generate\n * deterministic random numbers from a combination of key material and salt. It\n * serves as a key-stretching mechanism that can produce an arbitrary amount of\n * random-looking bytes from a single seed.\n *\n * Since it produces deterministic output based on the same inputs, it's useful\n * for situations where repeatable randomness is required, such as in testing\n * or when deterministically deriving keys from a master seed.\n *\n * Security considerations:\n * - The security of the generator depends on the entropy and secrecy of the\n * key material\n * - The same key material and salt will always produce the same sequence\n * - Use a secure random seed for cryptographic applications\n * - Never reuse the same HKDFRng instance for different purposes\n *\n * The implementation automatically handles buffer management, fetching new\n * data using HKDF as needed with an incrementing counter to ensure unique\n * output for each request.\n *\n * @example\n * ```typescript\n * import { HKDFRng } from '@bcts/components';\n *\n * // Create an HKDF-based RNG\n * const rng = HKDFRng.new(new TextEncoder().encode(\"my secure seed\"), \"wallet-derivation\");\n *\n * // Generate two u32 values\n * const random1 = rng.nextU32();\n * const random2 = rng.nextU32();\n *\n * // The same seed and salt will always produce the same sequence\n * const rng2 = HKDFRng.new(new TextEncoder().encode(\"my secure seed\"), \"wallet-derivation\");\n * console.log(random1 === rng2.nextU32()); // true\n * console.log(random2 === rng2.nextU32()); // true\n * ```\n */\n\nimport { hkdfHmacSha256 } from \"@bcts/crypto\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\n\nconst DEFAULT_PAGE_LENGTH = 32;\n\n/**\n * A deterministic random number generator based on HKDF-HMAC-SHA256.\n *\n * Implements the RandomNumberGenerator interface from @bcts/rand.\n */\nexport class HKDFRng implements RandomNumberGenerator {\n /** Internal buffer of generated bytes */\n private _buffer: Uint8Array;\n /** Current position in the buffer */\n private _position: number;\n /** Source key material (seed) */\n private readonly _keyMaterial: Uint8Array;\n /** Salt value to combine with the key material */\n private readonly _salt: string;\n /** Length of each \"page\" of generated data */\n private readonly _pageLength: number;\n /** Current page index */\n private _pageIndex: number;\n\n private constructor(keyMaterial: Uint8Array, salt: string, pageLength: number) {\n this._buffer = new Uint8Array(0);\n this._position = 0;\n this._keyMaterial = new Uint8Array(keyMaterial);\n this._salt = salt;\n this._pageLength = pageLength;\n this._pageIndex = 0;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Creates a new `HKDFRng` with a custom page length.\n *\n * @param keyMaterial - The seed material to derive random numbers from\n * @param salt - A salt value to mix with the key material\n * @param pageLength - The number of bytes to generate in each HKDF call\n * @returns A new `HKDFRng` instance configured with the specified parameters\n */\n static newWithPageLength(keyMaterial: Uint8Array, salt: string, pageLength: number): HKDFRng {\n return new HKDFRng(keyMaterial, salt, pageLength);\n }\n\n /**\n * Creates a new `HKDFRng` with the default page length of 32 bytes.\n *\n * @param keyMaterial - The seed material to derive random numbers from\n * @param salt - A salt value to mix with the key material\n * @returns A new `HKDFRng` instance configured with the specified key material and salt\n */\n static new(keyMaterial: Uint8Array, salt: string): HKDFRng {\n return HKDFRng.newWithPageLength(keyMaterial, salt, DEFAULT_PAGE_LENGTH);\n }\n\n // ============================================================================\n // Private Methods\n // ============================================================================\n\n /**\n * Refills the internal buffer with new deterministic random bytes.\n *\n * This method is called automatically when the internal buffer is exhausted.\n * It uses HKDF-HMAC-SHA256 to generate a new page of random bytes using the\n * key material, salt, and current page index.\n */\n private fillBuffer(): void {\n const saltString = `${this._salt}-${this._pageIndex}`;\n const encoder = new TextEncoder();\n this._buffer = hkdfHmacSha256(this._keyMaterial, encoder.encode(saltString), this._pageLength);\n this._position = 0;\n this._pageIndex += 1;\n }\n\n /**\n * Generates the specified number of deterministic random bytes.\n *\n * @param length - The number of bytes to generate\n * @returns A Uint8Array containing the requested number of deterministic random bytes\n */\n private nextBytes(length: number): Uint8Array {\n const result: number[] = [];\n while (result.length < length) {\n if (this._position >= this._buffer.length) {\n this.fillBuffer();\n }\n const remaining = length - result.length;\n const available = this._buffer.length - this._position;\n const take = Math.min(remaining, available);\n for (let i = 0; i < take; i++) {\n result.push(this._buffer[this._position + i]);\n }\n this._position += take;\n }\n return new Uint8Array(result);\n }\n\n // ============================================================================\n // RandomNumberGenerator Implementation\n // ============================================================================\n\n /**\n * Generates deterministic random bytes.\n *\n * @param length - The number of bytes to generate\n * @returns A Uint8Array of random bytes\n */\n randomData(length: number): Uint8Array {\n return this.nextBytes(length);\n }\n\n /**\n * Fills the provided buffer with deterministic random bytes.\n *\n * @param dest - The buffer to fill with random bytes\n */\n fillBytes(dest: Uint8Array): void {\n const bytes = this.nextBytes(dest.length);\n dest.set(bytes);\n }\n\n // ============================================================================\n // Additional Methods (matching Rust RngCore interface)\n // ============================================================================\n\n /**\n * Generates a random `u32` value.\n *\n * @returns A deterministic random 32-bit unsigned integer\n */\n nextU32(): number {\n const bytes = this.nextBytes(4);\n // Little-endian byte order\n return bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24);\n }\n\n /**\n * Generates a random `u64` value.\n *\n * Note: JavaScript numbers can only safely represent integers up to 2^53 - 1,\n * so this returns a BigInt for full 64-bit precision.\n *\n * @returns A deterministic random 64-bit unsigned integer as BigInt\n */\n nextU64(): bigint {\n const bytes = this.nextBytes(8);\n // Little-endian byte order\n let result = BigInt(0);\n for (let i = 7; i >= 0; i--) {\n result = (result << BigInt(8)) | BigInt(bytes[i]);\n }\n return result;\n }\n\n /**\n * Attempts to fill the provided buffer with random bytes.\n * This implementation never fails.\n *\n * @param dest - The buffer to fill with random bytes\n */\n tryFillBytes(dest: Uint8Array): void {\n this.fillBytes(dest);\n }\n\n /**\n * Fills the provided buffer with deterministic random bytes.\n * Alias for fillBytes for interface compatibility.\n *\n * @param data - The buffer to fill with random bytes\n */\n fillRandomData(data: Uint8Array): void {\n this.fillBytes(data);\n }\n\n // ============================================================================\n // Accessors (for testing)\n // ============================================================================\n\n /**\n * Returns the key material (for testing purposes).\n */\n getKeyMaterial(): Uint8Array {\n return new Uint8Array(this._keyMaterial);\n }\n\n /**\n * Returns the salt (for testing purposes).\n */\n getSalt(): string {\n return this._salt;\n }\n\n /**\n * Returns the page length (for testing purposes).\n */\n getPageLength(): number {\n return this._pageLength;\n }\n\n /**\n * Returns the current page index (for testing purposes).\n */\n getPageIndex(): number {\n return this._pageIndex;\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * DigestProvider interface for types that can provide a cryptographic digest.\n *\n * Ported from bc-components-rust/src/digest_provider.rs\n *\n * A type that can provide a single unique digest that characterizes its contents.\n * This trait is used to define a common interface for objects that can produce\n * a cryptographic digest (hash) of their content.\n *\n * @example\n * ```typescript\n * import { DigestProvider, Digest } from '@bcts/components';\n *\n * class Document implements DigestProvider {\n * private content: Uint8Array;\n * private cachedDigest?: Digest;\n *\n * constructor(content: Uint8Array) {\n * this.content = content;\n * }\n *\n * digest(): Digest {\n * if (!this.cachedDigest) {\n * this.cachedDigest = Digest.fromImage(this.content);\n * }\n * return this.cachedDigest;\n * }\n * }\n * ```\n */\nimport type { Digest } from \"./digest.js\";\n\n/**\n * A type that can provide a single unique digest that characterizes its contents.\n *\n * Use Cases:\n * - Data integrity verification\n * - Unique identifier for an object based on its content\n * - Content-addressable storage implementation\n * - Comparing objects by their content rather than identity\n */\nexport interface DigestProvider {\n /**\n * Returns a digest that uniquely characterizes the content of the\n * implementing type.\n */\n digest(): Digest;\n}\n\n/**\n * Helper function to get a digest from a byte array.\n * This provides DigestProvider-like functionality for raw bytes.\n *\n * @param data - The byte array to hash\n * @returns A Promise resolving to a Digest of the data\n */\nexport async function digestFromBytes(data: Uint8Array): Promise<Digest> {\n // Dynamic import to avoid circular dependency\n const { Digest } = await import(\"./digest.js\");\n return Digest.fromImage(data);\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * A random nonce (\"number used once\").\n *\n * Ported from bc-components-rust/src/nonce.rs\n *\n * A `Nonce` is a cryptographic primitive consisting of a random or\n * pseudo-random number that is used only once in a cryptographic\n * communication. Nonces are often used in authentication protocols, encryption\n * algorithms, and digital signatures to prevent replay attacks and ensure\n * the uniqueness of encrypted messages.\n *\n * In this implementation, a `Nonce` is a 12-byte random value. The size is\n * chosen to be sufficiently large to prevent collisions while remaining\n * efficient for storage and transmission.\n *\n * # CBOR Serialization\n *\n * `Nonce` implements the CBOR tagged encoding interfaces, which means it can be\n * serialized to and deserialized from CBOR with a specific tag (TAG_NONCE = 40014).\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `Nonce` is represented as a\n * binary blob with the type \"nonce\".\n *\n * # Common Uses\n *\n * - In authenticated encryption schemes like AES-GCM or ChaCha20-Poly1305\n * - For initializing counters in counter-mode block ciphers\n * - In challenge-response authentication protocols\n * - To prevent replay attacks in secure communications\n *\n * @example\n * ```typescript\n * import { Nonce } from '@bcts/components';\n *\n * // Generate a new random nonce\n * const nonce = Nonce.new();\n *\n * // Create a nonce from a byte array\n * const data = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);\n * const nonce2 = Nonce.fromData(data);\n *\n * // Access the nonce data\n * const nonceData = nonce2.data();\n * ```\n */\n\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\nimport { SYMMETRIC_NONCE_SIZE } from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { NONCE as TAG_NONCE } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"./error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"./utils.js\";\n\nexport class Nonce implements CborTaggedEncodable, CborTaggedDecodable<Nonce>, UREncodable {\n static readonly NONCE_SIZE = SYMMETRIC_NONCE_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== Nonce.NONCE_SIZE) {\n throw CryptoError.invalidSize(Nonce.NONCE_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new random nonce.\n */\n static new(): Nonce {\n const rng = new SecureRandomNumberGenerator();\n return new Nonce(rng.randomData(Nonce.NONCE_SIZE));\n }\n\n /**\n * Create a new random nonce (alias for compatibility).\n */\n static random(): Nonce {\n return Nonce.new();\n }\n\n /**\n * Restores a nonce from data.\n */\n static fromData(data: Uint8Array): Nonce {\n return new Nonce(new Uint8Array(data));\n }\n\n /**\n * Restores a nonce from data (validates length).\n */\n static fromDataRef(data: Uint8Array): Nonce {\n if (data.length !== Nonce.NONCE_SIZE) {\n throw CryptoError.invalidSize(Nonce.NONCE_SIZE, data.length);\n }\n return Nonce.fromData(data);\n }\n\n /**\n * Create a Nonce from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): Nonce {\n return Nonce.fromData(data);\n }\n\n /**\n * Create a new nonce from the given hexadecimal string.\n *\n * @throws Error if the string is not exactly 24 hexadecimal digits.\n */\n static fromHex(hex: string): Nonce {\n return new Nonce(hexToBytes(hex));\n }\n\n /**\n * Generate a random nonce using provided RNG.\n */\n static randomUsing(rng: SecureRandomNumberGenerator): Nonce {\n return new Nonce(rng.randomData(Nonce.NONCE_SIZE));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get the data of the nonce.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the nonce as a byte slice.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw nonce bytes as a copy.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * The data as a hexadecimal string.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Compare with another Nonce.\n */\n equals(other: Nonce): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `Nonce(${this.hex()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with Nonce.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_NONCE.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a Nonce by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): Nonce {\n const data = expectBytes(cbor);\n return Nonce.fromDataRef(data);\n }\n\n /**\n * Creates a Nonce by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): Nonce {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): Nonce {\n const instance = new Nonce(new Uint8Array(Nonce.NONCE_SIZE));\n return instance.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): Nonce {\n const cbor = decodeCbor(data);\n return Nonce.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): Nonce {\n const cbor = decodeCbor(data);\n const bytes = expectBytes(cbor);\n return Nonce.fromDataRef(bytes);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the Nonce.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"nonce\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a Nonce from a UR.\n */\n static fromUR(ur: UR): Nonce {\n ur.checkType(\"nonce\");\n const instance = new Nonce(new Uint8Array(Nonce.NONCE_SIZE));\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a Nonce from a UR string.\n */\n static fromURString(urString: string): Nonce {\n const ur = UR.fromURString(urString);\n return Nonce.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Random salt used to decorrelate other information.\n *\n * Ported from bc-components-rust/src/salt.rs\n *\n * A `Salt` is a cryptographic primitive consisting of random data that is used\n * to modify the output of a cryptographic function. Salts are primarily used\n * in password hashing to defend against dictionary attacks, rainbow table\n * attacks, and pre-computation attacks. They are also used in other\n * cryptographic contexts to ensure uniqueness and prevent correlation between\n * different parts of a cryptosystem.\n *\n * Unlike a `Nonce` which has a fixed size, a `Salt` in this implementation can\n * have a variable length (minimum 8 bytes). Different salt creation methods\n * are provided to generate salts of appropriate sizes for different use cases.\n *\n * # Minimum Size Requirement\n *\n * For security reasons, salts must be at least 8 bytes long. Attempting to\n * create a salt with fewer than 8 bytes will result in an error.\n *\n * # CBOR Serialization\n *\n * `Salt` implements the CBOR tagged encoding interfaces, which means it can be\n * serialized to and deserialized from CBOR with a specific tag (TAG_SALT = 40018).\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `Salt` is represented as a\n * binary blob with the type \"salt\".\n *\n * # Common Uses\n *\n * - Password hashing and key derivation functions\n * - Preventing correlation in cryptographic protocols\n * - Randomizing data before encryption to prevent pattern recognition\n * - Adding entropy to improve security in various cryptographic functions\n *\n * @example\n * ```typescript\n * import { Salt } from '@bcts/components';\n *\n * // Generate a salt with 16 bytes\n * const salt = Salt.newWithLen(16);\n * console.log(salt.len()); // 16\n *\n * // Generate a salt proportional to 100 bytes of data\n * const salt2 = Salt.newForSize(100);\n *\n * // Generate a salt with length between 16 and 32 bytes\n * const salt3 = Salt.newInRange(16, 32);\n * ```\n */\n\nimport {\n SecureRandomNumberGenerator,\n type RandomNumberGenerator,\n rngNextInClosedRangeI32,\n} from \"@bcts/rand\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { SALT as TAG_SALT } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"./error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"./utils.js\";\n\nconst MIN_SALT_SIZE = 8;\n\nexport class Salt implements CborTaggedEncodable, CborTaggedDecodable<Salt>, UREncodable {\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new salt from data.\n * Note: Does not validate minimum size to allow for CBOR deserialization.\n */\n static fromData(data: Uint8Array): Salt {\n return new Salt(new Uint8Array(data));\n }\n\n /**\n * Create a Salt from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): Salt {\n return Salt.fromData(data);\n }\n\n /**\n * Create a new salt from the given hexadecimal string.\n */\n static fromHex(hex: string): Salt {\n return Salt.fromData(hexToBytes(hex));\n }\n\n /**\n * Create a specific number of bytes of salt.\n *\n * @throws Error if the number of bytes is less than 8.\n */\n static newWithLen(count: number): Salt {\n const rng = new SecureRandomNumberGenerator();\n return Salt.newWithLenUsing(count, rng);\n }\n\n /**\n * Create a specific number of bytes of salt using provided RNG.\n *\n * @throws Error if the number of bytes is less than 8.\n */\n static newWithLenUsing(count: number, rng: RandomNumberGenerator): Salt {\n if (count < MIN_SALT_SIZE) {\n throw CryptoError.dataTooShort(\"salt\", MIN_SALT_SIZE, count);\n }\n return new Salt(rng.randomData(count));\n }\n\n /**\n * Create a number of bytes of salt chosen randomly from the given range.\n *\n * @throws Error if the minimum number of bytes is less than 8.\n */\n static newInRange(minSize: number, maxSize: number): Salt {\n if (minSize < MIN_SALT_SIZE) {\n throw CryptoError.dataTooShort(\"salt\", MIN_SALT_SIZE, minSize);\n }\n const rng = new SecureRandomNumberGenerator();\n return Salt.newInRangeUsing(minSize, maxSize, rng);\n }\n\n /**\n * Create a number of bytes of salt chosen randomly from the given range using provided RNG.\n *\n * @throws Error if the minimum number of bytes is less than 8.\n */\n static newInRangeUsing(minSize: number, maxSize: number, rng: RandomNumberGenerator): Salt {\n if (minSize < MIN_SALT_SIZE) {\n throw CryptoError.dataTooShort(\"salt\", MIN_SALT_SIZE, minSize);\n }\n const count = rngNextInClosedRangeI32(rng, minSize, maxSize);\n return Salt.newWithLenUsing(count, rng);\n }\n\n /**\n * Create a number of bytes of salt generally proportionate to the size of\n * the object being salted.\n */\n static newForSize(size: number): Salt {\n const rng = new SecureRandomNumberGenerator();\n return Salt.newForSizeUsing(size, rng);\n }\n\n /**\n * Create a number of bytes of salt generally proportionate to the size of\n * the object being salted using provided RNG.\n */\n static newForSizeUsing(size: number, rng: RandomNumberGenerator): Salt {\n const count = size;\n const minSize = Math.max(MIN_SALT_SIZE, Math.ceil(count * 0.05));\n const maxSize = Math.max(minSize + 8, Math.ceil(count * 0.25));\n return Salt.newInRangeUsing(minSize, maxSize, rng);\n }\n\n /**\n * Generate a random salt with specified size (legacy alias for newWithLen).\n */\n static random(size = 16): Salt {\n return Salt.newWithLen(size);\n }\n\n /**\n * Generate a random salt with specified size using provided RNG (legacy alias).\n */\n static randomUsing(rng: RandomNumberGenerator, size = 16): Salt {\n return Salt.newWithLenUsing(size, rng);\n }\n\n /**\n * Generate a proportionally-sized salt (legacy alias for newForSize).\n */\n static proportional(dataSize: number): Salt {\n return Salt.newForSize(dataSize);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Return the length of the salt.\n */\n len(): number {\n return this._data.length;\n }\n\n /**\n * Return the length of the salt (alias for len).\n */\n size(): number {\n return this.len();\n }\n\n /**\n * Return true if the salt is empty (this is not recommended).\n */\n isEmpty(): boolean {\n return this._data.length === 0;\n }\n\n /**\n * Return the data of the salt.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw salt bytes as a copy.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * The data as a hexadecimal string.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Compare with another Salt.\n */\n equals(other: Salt): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation showing the salt's length.\n */\n toString(): string {\n return `Salt(${this.len()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with Salt.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SALT.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a Salt by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): Salt {\n const data = expectBytes(cbor);\n return Salt.fromData(data);\n }\n\n /**\n * Creates a Salt by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): Salt {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): Salt {\n const instance = new Salt(new Uint8Array(0));\n return instance.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): Salt {\n const cbor = decodeCbor(data);\n return Salt.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): Salt {\n const cbor = decodeCbor(data);\n const bytes = expectBytes(cbor);\n return Salt.fromData(bytes);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the Salt.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"salt\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a Salt from a UR.\n */\n static fromUR(ur: UR): Salt {\n ur.checkType(\"salt\");\n const instance = new Salt(new Uint8Array(0));\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a Salt from a UR string.\n */\n static fromURString(urString: string): Salt {\n const ur = UR.fromURString(urString);\n return Salt.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Cryptographic seed with optional metadata (minimum 16 bytes)\n * Ported from bc-components-rust/src/seed.rs\n *\n * A `Seed` is a source of entropy used to generate cryptographic keys in a\n * deterministic manner. Unlike randomly generated keys, seed-derived keys can\n * be recreated if you have the original seed, making them useful for backup\n * and recovery scenarios.\n *\n * This implementation of `Seed` includes the random seed data as well as\n * optional metadata:\n * - A name (for identifying the seed)\n * - A note (for storing additional information)\n * - A creation date\n *\n * The minimum seed length is 16 bytes to ensure sufficient security and\n * entropy.\n *\n * # CBOR Serialization\n *\n * `Seed` implements the CBOR tagged encoding interfaces, which means it can be\n * serialized to and deserialized from CBOR with specific tags. The tags used\n * are `TAG_SEED` (40300) and the older `TAG_SEED_V1` (300) for backward compatibility.\n *\n * When serialized to CBOR, a `Seed` is represented as a map with the following\n * keys:\n * - 1: The seed data (required)\n * - 2: The creation date (optional)\n * - 3: The name (optional, omitted if empty)\n * - 4: The note (optional, omitted if empty)\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `Seed` is represented with the\n * type \"seed\".\n */\n\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n CborMap,\n CborDate,\n toByteString,\n expectMap,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { SEED as TAG_SEED, SEED_V1 as TAG_SEED_V1 } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"./error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"./utils.js\";\nimport type { PrivateKeyDataProvider } from \"./private-key-data-provider.js\";\n\nexport interface SeedMetadata {\n name?: string;\n note?: string;\n createdAt?: Date;\n}\n\nexport class Seed\n implements CborTaggedEncodable, CborTaggedDecodable<Seed>, UREncodable, PrivateKeyDataProvider\n{\n /**\n * Minimum seed length in bytes (matches Rust MIN_SEED_LENGTH).\n */\n static readonly MIN_SEED_LENGTH = 16;\n\n // Defensive copy: internal data is never exposed directly to prevent external mutation\n private readonly _data: Uint8Array;\n private _name: string;\n private _note: string;\n private _creationDate: Date | undefined;\n\n private constructor(data: Uint8Array, name?: string, note?: string, creationDate?: Date) {\n if (data.length < Seed.MIN_SEED_LENGTH) {\n throw CryptoError.dataTooShort(\"seed\", Seed.MIN_SEED_LENGTH, data.length);\n }\n // Defensive copy on construction to ensure immutability of internal state\n this._data = new Uint8Array(data);\n this._name = name ?? \"\";\n this._note = note ?? \"\";\n this._creationDate = creationDate;\n }\n\n // ============================================================================\n // Static Factory Methods (Rust API Parity)\n // ============================================================================\n\n /**\n * Create a new random seed with default length (16 bytes).\n *\n * Rust equivalent: `Seed::new()`\n */\n static new(): Seed {\n return Seed.newWithLen(Seed.MIN_SEED_LENGTH);\n }\n\n /**\n * Create a new random seed with a specified length.\n *\n * Rust equivalent: `Seed::new_with_len(count)`\n *\n * @param count - Number of bytes (must be >= 16)\n * @throws CryptoError if count < 16\n */\n static newWithLen(count: number): Seed {\n const rng = new SecureRandomNumberGenerator();\n return Seed.newWithLenUsing(count, rng);\n }\n\n /**\n * Create a new random seed with a specified length using provided RNG.\n *\n * Rust equivalent: `Seed::new_with_len_using(count, rng)`\n *\n * @param count - Number of bytes (must be >= 16)\n * @param rng - Random number generator\n * @throws CryptoError if count < 16\n */\n static newWithLenUsing(count: number, rng: { randomData: (size: number) => Uint8Array }): Seed {\n const data = rng.randomData(count);\n return Seed.newOpt(data, undefined, undefined, undefined);\n }\n\n /**\n * Create a new seed from data and optional metadata.\n *\n * Rust equivalent: `Seed::new_opt(data, name, note, creation_date)`\n *\n * @param data - Seed bytes (must be >= 16 bytes)\n * @param name - Optional name for the seed\n * @param note - Optional note for the seed\n * @param creationDate - Optional creation date\n * @throws CryptoError if data < 16 bytes\n */\n static newOpt(\n data: Uint8Array,\n name: string | undefined,\n note: string | undefined,\n creationDate: Date | undefined,\n ): Seed {\n return new Seed(data, name, note, creationDate);\n }\n\n // ============================================================================\n // Static Factory Methods (TypeScript Convenience)\n // ============================================================================\n\n /**\n * Create a Seed from raw bytes with optional metadata.\n *\n * Note: The input data is copied to prevent external mutation of the seed's internal state.\n *\n * @param data - Seed bytes (must be >= 16 bytes)\n * @param metadata - Optional metadata object\n */\n static from(data: Uint8Array, metadata?: SeedMetadata): Seed {\n return new Seed(new Uint8Array(data), metadata?.name, metadata?.note, metadata?.createdAt);\n }\n\n /**\n * Create a Seed from hex string with optional metadata.\n *\n * @param hex - Hex string representing seed bytes\n * @param metadata - Optional metadata object\n */\n static fromHex(hex: string, metadata?: SeedMetadata): Seed {\n return Seed.from(hexToBytes(hex), metadata);\n }\n\n /**\n * Generate a random seed with specified size (default 32 bytes).\n *\n * Convenience method that wraps `newWithLen()`.\n *\n * @param size - Number of bytes (must be >= 16, default 32)\n * @param metadata - Optional metadata object\n */\n static random(size = 32, metadata?: SeedMetadata): Seed {\n const seed = Seed.newWithLen(size);\n if (metadata?.name !== undefined) seed.setName(metadata.name);\n if (metadata?.note !== undefined) seed.setNote(metadata.note);\n if (metadata?.createdAt !== undefined) seed.setCreationDate(metadata.createdAt);\n return seed;\n }\n\n /**\n * Generate a random seed using provided RNG.\n *\n * Convenience method that wraps `newWithLenUsing()`.\n *\n * @param rng - Random number generator\n * @param size - Number of bytes (must be >= 16, default 32)\n * @param metadata - Optional metadata object\n */\n static randomUsing(\n rng: { randomData: (size: number) => Uint8Array },\n size = 32,\n metadata?: SeedMetadata,\n ): Seed {\n const seed = Seed.newWithLenUsing(size, rng);\n if (metadata?.name !== undefined) seed.setName(metadata.name);\n if (metadata?.note !== undefined) seed.setNote(metadata.note);\n if (metadata?.createdAt !== undefined) seed.setCreationDate(metadata.createdAt);\n return seed;\n }\n\n // ============================================================================\n // Instance Methods - Data Access (Rust API Parity)\n // ============================================================================\n\n /**\n * Return the data of the seed as a reference to the internal bytes.\n *\n * Rust equivalent: `seed.as_bytes()`\n *\n * Note: Returns a reference to internal data. For a copy, use `toData()`.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw seed bytes (copy).\n *\n * Note: Returns a copy to prevent external mutation of the seed's internal state.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n toHex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Get seed size in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n // ============================================================================\n // Instance Methods - Metadata Access (Rust API Parity)\n // ============================================================================\n\n /**\n * Return the name of the seed.\n *\n * Rust equivalent: `seed.name()` - returns empty string if not set.\n */\n name(): string {\n return this._name;\n }\n\n /**\n * Set the name of the seed.\n *\n * Rust equivalent: `seed.set_name(name)`\n */\n setName(name: string): void {\n this._name = name;\n }\n\n /**\n * Return the note of the seed.\n *\n * Rust equivalent: `seed.note()` - returns empty string if not set.\n */\n note(): string {\n return this._note;\n }\n\n /**\n * Set the note of the seed.\n *\n * Rust equivalent: `seed.set_note(note)`\n */\n setNote(note: string): void {\n this._note = note;\n }\n\n /**\n * Return the creation date of the seed.\n *\n * Rust equivalent: `seed.creation_date()`\n */\n creationDate(): Date | undefined {\n return this._creationDate;\n }\n\n /**\n * Set the creation date of the seed.\n *\n * Rust equivalent: `seed.set_creation_date(date)`\n */\n setCreationDate(creationDate: Date | undefined): void {\n this._creationDate = creationDate;\n }\n\n /**\n * Return the creation date of the seed (alias for creationDate).\n *\n * @deprecated Use `creationDate()` for Rust API parity.\n */\n createdAt(): Date | undefined {\n return this.creationDate();\n }\n\n /**\n * Set the creation date of the seed (alias for setCreationDate).\n *\n * @deprecated Use `setCreationDate()` for Rust API parity.\n */\n setCreatedAt(date: Date): void {\n this.setCreationDate(date);\n }\n\n /**\n * Get metadata as an object.\n *\n * TypeScript convenience method - returns a snapshot of current metadata.\n */\n getMetadata(): SeedMetadata {\n const metadata: SeedMetadata = {};\n if (this._name.length > 0) {\n metadata.name = this._name;\n }\n if (this._note.length > 0) {\n metadata.note = this._note;\n }\n if (this._creationDate !== undefined) {\n metadata.createdAt = this._creationDate;\n }\n return metadata;\n }\n\n // ============================================================================\n // Instance Methods - Comparison and Display\n // ============================================================================\n\n /**\n * Compare with another Seed.\n */\n equals(other: Seed): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `Seed(${this.toHex().substring(0, 16)}..., ${this.size()} bytes)`;\n }\n\n // ============================================================================\n // PrivateKeyDataProvider Implementation\n // ============================================================================\n\n /**\n * Returns unique data from which cryptographic keys can be derived.\n *\n * This implementation returns a copy of the seed data, which can be used\n * as entropy for deriving private keys in various cryptographic schemes.\n *\n * @returns A Uint8Array containing the seed data\n */\n privateKeyData(): Uint8Array {\n return this.toData();\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with Seed.\n * Includes TAG_SEED (40300) and TAG_SEED_V1 (300) for backward compatibility.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SEED.value, TAG_SEED_V1.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a map).\n * Map keys:\n * - 1: seed data (required)\n * - 2: creation date (optional)\n * - 3: name (optional, omitted if empty)\n * - 4: note (optional, omitted if empty)\n */\n untaggedCbor(): Cbor {\n const map = CborMap.new();\n map.insert(1, toByteString(this._data));\n if (this._creationDate !== undefined) {\n const cborDate = CborDate.fromDatetime(this._creationDate);\n map.insert(2, cborDate.taggedCbor());\n }\n if (this._name.length > 0) {\n map.insert(3, this._name);\n }\n if (this._note.length > 0) {\n map.insert(4, this._note);\n }\n return cbor(map);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a Seed by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): Seed {\n const map = expectMap(cborValue);\n\n // Key 1: seed data (required)\n // CborMap.extract() returns native types (Uint8Array for byte strings)\n const data = map.extract<number, Uint8Array>(1);\n if (data.length === 0) {\n throw CryptoError.invalidData(\"Seed data is empty\");\n }\n\n // Key 2: creation date (optional)\n // For tagged values (like dates), the extract returns the tagged Cbor object\n let creationDate: Date | undefined;\n const dateValue = map.get<number, Cbor>(2);\n if (dateValue !== undefined) {\n // The date is stored as a tagged CBOR value (tag 1)\n const cborDate = CborDate.fromTaggedCbor(cbor(dateValue));\n creationDate = cborDate.datetime();\n }\n\n // Key 3: name (optional)\n const name = map.get<number, string>(3);\n\n // Key 4: note (optional)\n const note = map.get<number, string>(4);\n\n return Seed.newOpt(new Uint8Array(data), name, note, creationDate);\n }\n\n /**\n * Creates a Seed by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): Seed {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): Seed {\n const instance = Seed.new();\n return instance.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): Seed {\n const cborValue = decodeCbor(data);\n return Seed.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): Seed {\n const cborValue = decodeCbor(data);\n const instance = Seed.new();\n return instance.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the Seed.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"seed\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a Seed from a UR.\n */\n static fromUR(ur: UR): Seed {\n ur.checkType(\"seed\");\n const instance = Seed.new();\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a Seed from a UR string.\n */\n static fromURString(urString: string): Seed {\n const ur = UR.fromURString(urString);\n return Seed.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Content-addressable reference - SHA-256 digest with short reference encoding\n */\n\nimport { Digest } from \"./digest.js\";\nimport { CryptoError } from \"./error.js\";\n\nexport type ReferenceEncodingFormat = \"hex\" | \"bytewords\" | \"bytemojis\";\n\n/**\n * Implementers of this interface provide a globally unique reference to themselves.\n *\n * The `ReferenceProvider` interface is used to create a unique, cryptographic\n * reference to an object. This is particularly useful for distributed systems\n * where objects need to be uniquely identified across networks or storage\n * systems.\n *\n * The reference is derived from a cryptographic digest of the object's\n * serialized form, ensuring that the reference uniquely identifies the\n * object's contents.\n */\nexport interface ReferenceProvider {\n /**\n * Returns a cryptographic reference that uniquely identifies this object.\n *\n * The reference is derived from a digest of the object's serialized form,\n * ensuring that it uniquely identifies the object's contents.\n */\n reference(): Reference;\n}\n\n/**\n * Type guard to check if an object implements the ReferenceProvider interface.\n */\nexport function isReferenceProvider(obj: unknown): obj is ReferenceProvider {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"reference\" in obj &&\n typeof (obj as ReferenceProvider).reference === \"function\"\n );\n}\n\n// Bytewords mapping (256 words)\nconst BYTEWORDS = [\n \"abled\",\n \"ache\",\n \"acid\",\n \"acme\",\n \"acre\",\n \"aged\",\n \"aide\",\n \"airy\",\n \"ajar\",\n \"akin\",\n \"alas\",\n \"alba\",\n \"alee\",\n \"alms\",\n \"aloe\",\n \"also\",\n \"ante\",\n \"anti\",\n \"ants\",\n \"anus\",\n \"anus\",\n \"apes\",\n \"apex\",\n \"apse\",\n \"arch\",\n \"area\",\n \"ares\",\n \"aria\",\n \"arid\",\n \"ark\",\n \"arms\",\n \"army\",\n // ... (256 total - abbreviated for space)\n];\n\n// Bytemojis mapping (256 emojis)\nconst BYTEMOJIS = [\n \"😀\",\n \"😂\",\n \"😆\",\n \"😉\",\n \"😊\",\n \"😌\",\n \"😎\",\n \"😏\",\n \"😑\",\n \"😒\",\n \"😓\",\n \"😔\",\n \"😕\",\n \"😖\",\n \"😗\",\n \"😘\",\n // ... (256 total - abbreviated for space)\n];\n\nexport class Reference {\n private readonly digest: Digest;\n\n private constructor(digest: Digest) {\n this.digest = digest;\n }\n\n /**\n * Create a Reference from a Digest\n */\n static from(digest: Digest): Reference {\n return new Reference(digest);\n }\n\n /**\n * Create a Reference from hex string\n */\n static fromHex(hex: string): Reference {\n const digest = Digest.fromHex(hex);\n return new Reference(digest);\n }\n\n /**\n * Generate a Reference from data\n */\n static hash(data: Uint8Array): Reference {\n const digest = Digest.hash(data);\n return new Reference(digest);\n }\n\n /**\n * Get the underlying Digest\n */\n getDigest(): Digest {\n return this.digest;\n }\n\n /**\n * Get full reference as hex string\n */\n toHex(): string {\n return this.digest.toHex();\n }\n\n /**\n * Get short reference (first 4 bytes) in various formats\n */\n shortReference(format: ReferenceEncodingFormat = \"hex\"): string {\n const data = this.digest.toData();\n const shortData = data.slice(0, 4);\n\n switch (format) {\n case \"hex\":\n // Lowercase hex, matching Rust implementation\n return Array.from(shortData)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n\n case \"bytewords\":\n return Array.from(shortData)\n .map((b) => BYTEWORDS[b] ?? `word${b}`)\n .join(\" \");\n\n case \"bytemojis\":\n return Array.from(shortData)\n .map((b) => BYTEMOJIS[b] ?? \"❓\")\n .join(\" \");\n\n default: {\n const _exhaustive: never = format;\n throw CryptoError.invalidFormat(`Unknown reference format: ${String(_exhaustive)}`);\n }\n }\n }\n\n /**\n * Get full reference as hex string (alias for toHex)\n */\n fullReference(): string {\n return this.toHex();\n }\n\n /**\n * Get short reference as hex string.\n * Convenience method for parity with Rust's ref_hex_short().\n */\n refHexShort(): string {\n return this.shortReference(\"hex\");\n }\n\n /**\n * Get base64 representation\n */\n toBase64(): string {\n return this.digest.toBase64();\n }\n\n /**\n * Compare with another Reference\n */\n equals(other: Reference): boolean {\n return this.digest.equals(other.digest);\n }\n\n /**\n * Get string representation\n */\n toString(): string {\n return `Reference(${this.shortReference(\"hex\")})`;\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * An \"Apparently Random Identifier\" (ARID)\n *\n * Ported from bc-components-rust/src/id/arid.rs\n *\n * An ARID is a cryptographically strong, universally unique identifier with\n * the following properties:\n * - Non-correlatability: The sequence of bits cannot be correlated with its\n * referent or any other ARID\n * - Neutral semantics: Contains no inherent type information\n * - Open generation: Any method of generation is allowed as long as it\n * produces statistically random bits\n * - Minimum strength: Must be 256 bits (32 bytes) in length\n * - Cryptographic suitability: Can be used as inputs to cryptographic\n * constructs\n *\n * Unlike digests/hashes which identify a fixed, immutable state of data, ARIDs\n * can serve as stable identifiers for mutable data structures.\n *\n * ARIDs should not be confused with or cast to/from other identifier types\n * (like UUIDs), used as nonces, keys, or cryptographic seeds.\n *\n * As defined in [BCR-2022-002](https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2022-002-arid.md).\n *\n * # CBOR Serialization\n *\n * `ARID` implements the CBOR tagged encoding interfaces, which means it can be\n * serialized to and deserialized from CBOR with a specific tag (TAG_ARID = 40012).\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), an `ARID` is represented as a\n * binary blob with the type \"arid\".\n *\n * @example\n * ```typescript\n * import { ARID } from '@bcts/components';\n *\n * // Create a new random ARID\n * const arid = ARID.new();\n *\n * // Create an ARID from a hex string\n * const arid2 = ARID.fromHex(\"...\");\n *\n * // Get the ARID as hex\n * console.log(arid.hex());\n * ```\n */\n\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { ARID as TAG_ARID } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\n\nexport class ARID implements CborTaggedEncodable, CborTaggedDecodable<ARID>, UREncodable {\n static readonly ARID_SIZE = 32;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== ARID.ARID_SIZE) {\n throw CryptoError.invalidSize(ARID.ARID_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new random ARID.\n */\n static new(): ARID {\n const rng = new SecureRandomNumberGenerator();\n return new ARID(rng.randomData(ARID.ARID_SIZE));\n }\n\n /**\n * Create a new random ARID (alias for new()).\n */\n static random(): ARID {\n return ARID.new();\n }\n\n /**\n * Restore an ARID from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): ARID {\n return new ARID(new Uint8Array(data));\n }\n\n /**\n * Create a new ARID from a reference to an array of bytes.\n */\n static fromDataRef(data: Uint8Array): ARID {\n if (data.length !== ARID.ARID_SIZE) {\n throw CryptoError.invalidSize(ARID.ARID_SIZE, data.length);\n }\n return ARID.fromData(data);\n }\n\n /**\n * Create an ARID from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): ARID {\n return ARID.fromData(data);\n }\n\n /**\n * Create a new ARID from the given hexadecimal string.\n *\n * @throws Error if the string is not exactly 64 hexadecimal digits.\n */\n static fromHex(hex: string): ARID {\n return new ARID(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get the data of the ARID as an array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the data of the ARID as a byte slice.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw ARID bytes as a copy.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * The data as a hexadecimal string.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * The first four bytes of the ARID as a hexadecimal string.\n */\n shortDescription(): string {\n return bytesToHex(this._data.slice(0, 4));\n }\n\n /**\n * Compare with another ARID.\n */\n equals(other: ARID): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Compare ARIDs lexicographically.\n */\n compare(other: ARID): number {\n for (let i = 0; i < this._data.length; i++) {\n const a = this._data[i];\n const b = other._data[i];\n if (a < b) return -1;\n if (a > b) return 1;\n }\n return 0;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `ARID(${this.hex()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with ARID.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_ARID.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an ARID by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): ARID {\n const data = expectBytes(cbor);\n return ARID.fromDataRef(data);\n }\n\n /**\n * Creates an ARID by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): ARID {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): ARID {\n const instance = new ARID(new Uint8Array(ARID.ARID_SIZE));\n return instance.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): ARID {\n const cbor = decodeCbor(data);\n return ARID.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): ARID {\n const cbor = decodeCbor(data);\n const bytes = expectBytes(cbor);\n return ARID.fromDataRef(bytes);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the ARID.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"arid\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an ARID from a UR.\n */\n static fromUR(ur: UR): ARID {\n ur.checkType(\"arid\");\n const instance = new ARID(new Uint8Array(ARID.ARID_SIZE));\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an ARID from a UR string.\n */\n static fromURString(urString: string): ARID {\n const ur = UR.fromURString(urString);\n return ARID.fromUR(ur);\n }\n\n /**\n * Alias for fromURString for Rust API compatibility.\n */\n static fromUrString(urString: string): ARID {\n return ARID.fromURString(urString);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Universally Unique Identifier (UUID) - 16-byte identifier\n *\n * UUIDs are 128-bit (16-byte) identifiers that are designed to be unique\n * across space and time. This implementation creates type 4 (random) UUIDs,\n * following the UUID specification:\n *\n * - Version field (bits 48-51) is set to 4, indicating a random UUID\n * - Variant field (bits 64-65) is set to 2, indicating RFC 4122/DCE 1.1 UUID\n * variant\n *\n * Unlike ARIDs, UUIDs:\n * - Are shorter (128 bits vs 256 bits)\n * - Contain version and variant metadata within the identifier\n * - Have a canonical string representation with 5 groups separated by hyphens\n *\n * The canonical textual representation of a UUID takes the form:\n * `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` where each `x` is a hexadecimal digit.\n *\n * # CBOR Serialization\n *\n * `UUID` is serialized to CBOR with tag 37 (standard UUID tag).\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `UUID` is represented with the\n * type \"uuid\".\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UUID as TAG_UUID } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, toBase64 } from \"../utils.js\";\n\nconst UUID_SIZE = 16;\n\nexport class UUID implements CborTaggedEncodable, CborTaggedDecodable<UUID>, UREncodable {\n static readonly UUID_SIZE = UUID_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== UUID_SIZE) {\n throw CryptoError.invalidSize(UUID_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new random UUID (v4).\n */\n static new(): UUID {\n return UUID.random();\n }\n\n /**\n * Create a UUID from raw bytes.\n */\n static fromData(data: Uint8Array): UUID {\n return new UUID(new Uint8Array(data));\n }\n\n /**\n * Restores a UUID from data (validates length).\n */\n static fromDataRef(data: Uint8Array): UUID {\n if (data.length !== UUID_SIZE) {\n throw CryptoError.invalidSize(UUID_SIZE, data.length);\n }\n return UUID.fromData(data);\n }\n\n /**\n * Create a UUID from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): UUID {\n return UUID.fromData(data);\n }\n\n /**\n * Create a UUID from hex string (32 hex chars)\n */\n static fromHex(hex: string): UUID {\n if (hex.length !== 32) {\n throw CryptoError.invalidFormat(`UUID hex must be 32 characters, got ${hex.length}`);\n }\n const data = new Uint8Array(16);\n for (let i = 0; i < 16; i++) {\n data[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);\n }\n return new UUID(data);\n }\n\n /**\n * Create a UUID from string representation (standard UUID format)\n * Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n */\n static fromString(uuidString: string): UUID {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n if (!uuidRegex.test(uuidString)) {\n throw CryptoError.invalidFormat(`Invalid UUID format: ${uuidString}`);\n }\n const hex = uuidString.replace(/-/g, \"\");\n return UUID.fromHex(hex);\n }\n\n /**\n * Generate a random UUID (v4)\n */\n static random(): UUID {\n const data = new Uint8Array(UUID_SIZE);\n globalThis.crypto.getRandomValues(data);\n\n // Set version to 4 (random)\n data[6] = (data[6] & 0x0f) | 0x40;\n // Set variant to RFC 4122\n data[8] = (data[8] & 0x3f) | 0x80;\n\n return new UUID(data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get the data of the UUID.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the UUID as a byte slice.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw UUID bytes as a copy.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation (lowercase, matching Rust implementation).\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get standard UUID string representation.\n * Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n */\n toString(): string {\n const hex = this.toHex();\n return `${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}`;\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Compare with another UUID.\n */\n equals(other: UUID): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with UUID.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_UUID.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a UUID by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): UUID {\n const data = expectBytes(cbor);\n return UUID.fromDataRef(data);\n }\n\n /**\n * Creates a UUID by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): UUID {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): UUID {\n const instance = new UUID(new Uint8Array(UUID_SIZE));\n return instance.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): UUID {\n const cbor = decodeCbor(data);\n return UUID.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): UUID {\n const cbor = decodeCbor(data);\n const bytes = expectBytes(cbor);\n return UUID.fromDataRef(bytes);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the UUID.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"uuid\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a UUID from a UR.\n */\n static fromUR(ur: UR): UUID {\n ur.checkType(\"uuid\");\n const instance = new UUID(new Uint8Array(UUID_SIZE));\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a UUID from a UR string.\n */\n static fromURString(urString: string): UUID {\n const ur = UR.fromURString(urString);\n return UUID.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * eXtensible Identifier (XID) - 32-byte identifier bound to a public key\n *\n * A XID is a unique 32-byte identifier for a subject entity (person,\n * organization, device, or any other entity). XIDs have the following\n * characteristics:\n *\n * - They're cryptographically tied to a public key at inception (the\n * \"inception key\")\n * - They remain stable throughout their lifecycle even as their keys and\n * permissions change\n * - They can be extended to XID documents containing keys, endpoints,\n * permissions, and delegation info\n * - They support key rotation and multiple verification schemes\n * - They allow for delegation of specific permissions to other entities\n * - They can include resolution methods to locate and verify the XID document\n *\n * A XID is created by taking the SHA-256 hash of the CBOR encoding of a public\n * signing key. This ensures the XID is cryptographically tied to the key.\n *\n * As defined in [BCR-2024-010](https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2024-010-xid.md).\n *\n * # CBOR Serialization\n *\n * `XID` is serialized to CBOR with tag 40024 (standard XID tag).\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `XID` is represented with the\n * type \"xid\".\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { XID as TAG_XID } from \"@bcts/tags\";\nimport {\n UR,\n type UREncodable,\n encodeBytewordsIdentifier,\n encodeBytemojisIdentifier,\n} from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, toBase64 } from \"../utils.js\";\nimport { Digest } from \"../digest.js\";\nimport type { SigningPublicKey } from \"../signing/signing-public-key.js\";\n\n/** XID prefix for bytewords/bytemoji identifiers */\nconst XID_PREFIX = \"🅧\";\n\nconst XID_SIZE = 32;\n\nexport class XID implements CborTaggedEncodable, CborTaggedDecodable<XID>, UREncodable {\n static readonly XID_SIZE = XID_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== XID_SIZE) {\n throw CryptoError.invalidSize(XID_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new XID from data.\n */\n static fromData(data: Uint8Array): XID {\n return new XID(new Uint8Array(data));\n }\n\n /**\n * Create a new XID from data (validates length).\n *\n * Returns error if the data is not the correct length.\n */\n static fromDataRef(data: Uint8Array): XID {\n if (data.length !== XID_SIZE) {\n throw CryptoError.invalidSize(XID_SIZE, data.length);\n }\n return XID.fromData(data);\n }\n\n /**\n * Create an XID from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): XID {\n return XID.fromData(data);\n }\n\n /**\n * Create an XID from hex string (64 hex characters).\n */\n static fromHex(hex: string): XID {\n if (hex.length !== 64) {\n throw CryptoError.invalidFormat(`XID hex must be 64 characters, got ${hex.length}`);\n }\n const data = new Uint8Array(32);\n for (let i = 0; i < 32; i++) {\n data[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);\n }\n return new XID(data);\n }\n\n /**\n * Generate a random XID (for testing purposes).\n *\n * Note: In practice, XIDs should be created from the SHA-256 hash of a\n * public signing key's CBOR encoding.\n */\n static random(): XID {\n const data = new Uint8Array(XID_SIZE);\n const crypto = globalThis.crypto as Crypto | undefined;\n if (crypto !== undefined && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(data);\n } else {\n // Fallback: fill with available random data\n for (let i = 0; i < XID_SIZE; i++) {\n data[i] = Math.floor(Math.random() * 256);\n }\n }\n return new XID(data);\n }\n\n /**\n * Create a new XID from the given public key (the \"genesis key\").\n *\n * The XID is the SHA-256 digest of the CBOR encoding of the public key.\n * This matches Rust's `XID::new(genesis_key: impl AsRef<SigningPublicKey>)`.\n */\n static newFromSigningKey(signingPublicKey: SigningPublicKey): XID {\n const keyCborData = signingPublicKey.taggedCborData();\n const digest = Digest.fromImage(keyCborData);\n return XID.fromData(digest.toData());\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Validate the XID against the given public key.\n *\n * Returns true if the SHA-256 hash of the key's CBOR encoding matches\n * the XID data. This matches Rust's `XID::validate(&self, key: &SigningPublicKey)`.\n */\n validate(signingPublicKey: SigningPublicKey): boolean {\n const keyData = signingPublicKey.taggedCborData();\n const digest = Digest.fromImage(keyData);\n return this.equals(XID.fromData(digest.toData()));\n }\n\n /**\n * Return the data of the XID.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the data of the XID as a byte slice.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get a copy of the raw XID bytes.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation (lowercase, matching Rust implementation).\n */\n toHex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Get short description (first 4 bytes) as hex.\n */\n shortDescription(): string {\n return bytesToHex(this._data.slice(0, 4));\n }\n\n /**\n * Get short reference (first 4 bytes) as hex (alias for shortDescription).\n */\n shortReference(): string {\n return this.shortDescription();\n }\n\n /**\n * Get the first four bytes of the XID as upper-case ByteWords.\n *\n * @param prefix - If true, prepends the XID prefix \"🅧 \"\n * @returns Space-separated uppercase bytewords, e.g., \"🅧 URGE DICE GURU IRIS\"\n */\n bytewordsIdentifier(prefix = false): string {\n const words = encodeBytewordsIdentifier(this._data.slice(0, 4)).toUpperCase();\n return prefix ? `${XID_PREFIX} ${words}` : words;\n }\n\n /**\n * Get the first four bytes of the XID as Bytemoji.\n *\n * @param prefix - If true, prepends the XID prefix \"🅧 \"\n * @returns Space-separated emojis, e.g., \"🅧 🐻 😻 🍞 💐\"\n */\n bytemojisIdentifier(prefix = false): string {\n const emojis = encodeBytemojisIdentifier(this._data.slice(0, 4));\n return prefix ? `${XID_PREFIX} ${emojis}` : emojis;\n }\n\n /**\n * Compare with another XID.\n */\n equals(other: XID): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation (short format, matching Rust Display).\n * Uses first 4 bytes of the XID as hex, e.g., \"XID(71274df1)\".\n */\n toString(): string {\n return `XID(${this.shortDescription()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with XID.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_XID.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a XID by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): XID {\n const data = expectBytes(cbor);\n return XID.fromDataRef(data);\n }\n\n /**\n * Creates a XID by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): XID {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): XID {\n const instance = new XID(new Uint8Array(XID_SIZE));\n return instance.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): XID {\n const cbor = decodeCbor(data);\n return XID.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): XID {\n const cbor = decodeCbor(data);\n const bytes = expectBytes(cbor);\n return XID.fromDataRef(bytes);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the XID.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"xid\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a XID from a UR.\n */\n static fromUR(ur: UR): XID {\n ur.checkType(\"xid\");\n const instance = new XID(new Uint8Array(XID_SIZE));\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a XID from a UR string.\n */\n static fromURString(urString: string): XID {\n const ur = UR.fromURString(urString);\n return XID.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Uniform Resource Identifier (URI) - String-based identifier\n *\n * A URI is a string of characters that unambiguously identifies a particular\n * resource. This implementation validates URIs using the URL API to ensure\n * conformance to RFC 3986.\n *\n * URIs are commonly used for:\n * - Web addresses (URLs like \"https://example.com\")\n * - Resource identifiers in various protocols\n * - Namespace identifiers\n * - References to resources in distributed systems\n *\n * # CBOR Serialization\n *\n * `URI` is serialized to CBOR with tag 32 (standard URI tag).\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `URI` is represented with the\n * type \"url\".\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectText,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { URI as TAG_URI } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"../error.js\";\nimport { toBase64 } from \"../utils.js\";\n\nexport class URI implements CborTaggedEncodable, CborTaggedDecodable<URI>, UREncodable {\n private readonly _uri: string;\n\n private constructor(uri: string) {\n this._uri = uri;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Creates a new `URI` from a string with validation.\n */\n static new(uri: string): URI {\n // Validate using URL API\n try {\n new URL(uri);\n return new URI(uri);\n } catch {\n throw CryptoError.invalidData(\"URI: invalid URI format\");\n }\n }\n\n /**\n * Create a URI from string (legacy alias).\n */\n static from(uri: string): URI {\n return URI.new(uri);\n }\n\n /**\n * Parse a URI string (alias for new()).\n */\n static parse(uriString: string): URI {\n return URI.new(uriString);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get the URI as a string reference.\n */\n asRef(): string {\n return this._uri;\n }\n\n /**\n * Get the URI string.\n */\n toString(): string {\n return this._uri;\n }\n\n /**\n * Get the URI string (alias).\n */\n toURI(): string {\n return this._uri;\n }\n\n /**\n * Get the raw URI string.\n */\n getRaw(): string {\n return this._uri;\n }\n\n /**\n * Get scheme (e.g., \"http\", \"https\", \"urn\").\n */\n scheme(): string | null {\n const match = /^([a-z][a-z0-9+.-]*):\\/?\\/?/i.exec(this._uri);\n return match !== null ? match[1] : null;\n }\n\n /**\n * Get path component.\n */\n path(): string {\n try {\n const url = new URL(this._uri);\n return url.pathname;\n } catch {\n // For non-URL URIs, try to extract path after scheme\n const withoutScheme = this._uri.replace(/^[a-z][a-z0-9+.-]*:\\/?\\/?/i, \"\");\n return withoutScheme;\n }\n }\n\n /**\n * Check if URI is absolute (has a scheme).\n */\n isAbsolute(): boolean {\n return /^[a-z][a-z0-9+.-]*:/i.test(this._uri);\n }\n\n /**\n * Check if URI is relative.\n */\n isRelative(): boolean {\n return !this.isAbsolute();\n }\n\n /**\n * Compare with another URI.\n */\n equals(other: URI): boolean {\n return this._uri === other._uri;\n }\n\n /**\n * Check if URI starts with given prefix.\n */\n startsWith(prefix: string): boolean {\n return this._uri.startsWith(prefix);\n }\n\n /**\n * Get base64 representation of the URI string.\n */\n toBase64(): string {\n return toBase64(new TextEncoder().encode(this._uri));\n }\n\n /**\n * Get the length of the URI string.\n */\n length(): number {\n return this._uri.length;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with URI.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_URI.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a text string).\n */\n untaggedCbor(): Cbor {\n return cbor(this._uri);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a URI by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): URI {\n const text = expectText(cborValue);\n return URI.new(text);\n }\n\n /**\n * Creates a URI by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): URI {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): URI {\n const instance = new URI(\"https://placeholder.invalid\");\n return instance.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): URI {\n const cborValue = decodeCbor(data);\n return URI.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): URI {\n const cborValue = decodeCbor(data);\n const text = expectText(cborValue);\n return URI.new(text);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the URI.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"url\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a URI from a UR.\n */\n static fromUR(ur: UR): URI {\n ur.checkType(\"url\");\n const instance = new URI(\"https://placeholder.invalid\");\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a URI from a UR string.\n */\n static fromURString(urString: string): URI {\n const ur = UR.fromURString(urString);\n return URI.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * X25519 public key for ECDH key exchange (32 bytes)\n *\n * X25519 is an elliptic-curve Diffie-Hellman key exchange protocol based on\n * Curve25519 as defined in RFC 7748. It allows two parties to establish a\n * shared secret key over an insecure channel.\n *\n * The X25519 public key is generated from a corresponding private key and is\n * designed to be:\n * - Compact (32 bytes)\n * - Fast to use in key agreement operations\n * - Resistant to various cryptographic attacks\n *\n * # CBOR Serialization\n *\n * `X25519PublicKey` is serialized to CBOR with tag 40011.\n *\n * ```\n * #6.40011(h'<32-byte-public-key>')\n * ```\n *\n * Ported from bc-components-rust/src/x25519/x25519_public_key.rs\n */\n\nimport { X25519_PUBLIC_KEY_SIZE } from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { X25519_PUBLIC_KEY as TAG_X25519_PUBLIC_KEY } from \"@bcts/tags\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\n\nexport class X25519PublicKey\n implements CborTaggedEncodable, CborTaggedDecodable<X25519PublicKey>, UREncodable\n{\n static readonly KEY_SIZE = X25519_PUBLIC_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== X25519_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(X25519_PUBLIC_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Restore an X25519PublicKey from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): X25519PublicKey {\n return new X25519PublicKey(new Uint8Array(data));\n }\n\n /**\n * Restore an X25519PublicKey from a reference to an array of bytes.\n * Validates the length.\n */\n static fromDataRef(data: Uint8Array): X25519PublicKey {\n if (data.length !== X25519_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(X25519_PUBLIC_KEY_SIZE, data.length);\n }\n return X25519PublicKey.fromData(data);\n }\n\n /**\n * Create an X25519PublicKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): X25519PublicKey {\n return X25519PublicKey.fromData(data);\n }\n\n /**\n * Restore an X25519PublicKey from a hex string.\n */\n static fromHex(hex: string): X25519PublicKey {\n return X25519PublicKey.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw public key bytes (copy).\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Compare with another X25519PublicKey.\n */\n equals(other: X25519PublicKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `X25519PublicKey(${this.toHex().substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with X25519PublicKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_X25519_PUBLIC_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an X25519PublicKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): X25519PublicKey {\n const data = expectBytes(cbor);\n return X25519PublicKey.fromDataRef(data);\n }\n\n /**\n * Creates an X25519PublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): X25519PublicKey {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): X25519PublicKey {\n const dummy = new X25519PublicKey(new Uint8Array(X25519_PUBLIC_KEY_SIZE));\n return dummy.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): X25519PublicKey {\n const cbor = decodeCbor(data);\n return X25519PublicKey.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): X25519PublicKey {\n const cbor = decodeCbor(data);\n const dummy = new X25519PublicKey(new Uint8Array(X25519_PUBLIC_KEY_SIZE));\n return dummy.fromUntaggedCbor(cbor);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the X25519PublicKey.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n const name = TAG_X25519_PUBLIC_KEY.name;\n if (name === undefined) {\n throw new Error(\"X25519_PUBLIC_KEY tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an X25519PublicKey from a UR.\n */\n static fromUR(ur: UR): X25519PublicKey {\n const name = TAG_X25519_PUBLIC_KEY.name;\n if (name === undefined) {\n throw new Error(\"X25519_PUBLIC_KEY tag name is undefined\");\n }\n ur.checkType(name);\n const dummy = new X25519PublicKey(new Uint8Array(X25519_PUBLIC_KEY_SIZE));\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an X25519PublicKey from a UR string.\n */\n static fromURString(urString: string): X25519PublicKey {\n const ur = UR.fromURString(urString);\n return X25519PublicKey.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Authentication tag for AEAD encryption (16 bytes)\n *\n * An `AuthenticationTag` is a 16-byte value generated during ChaCha20-Poly1305\n * authenticated encryption. It serves as a message authentication code (MAC)\n * that verifies both the authenticity and integrity of the encrypted message.\n *\n * During decryption, the tag is verified to ensure:\n * - The message has not been tampered with (integrity)\n * - The message was encrypted by someone who possesses the encryption key\n * (authenticity)\n *\n * This implementation follows the Poly1305 MAC algorithm as specified in\n * [RFC-8439](https://datatracker.ietf.org/doc/html/rfc8439).\n *\n * Ported from bc-components-rust/src/symmetric/authentication_tag.rs\n */\n\nimport { type Cbor, toByteString, expectBytes, decodeCbor } from \"@bcts/dcbor\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\n\nconst AUTHENTICATION_TAG_SIZE = 16;\n\nexport class AuthenticationTag {\n static readonly AUTHENTICATION_TAG_SIZE = AUTHENTICATION_TAG_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== AUTHENTICATION_TAG_SIZE) {\n throw CryptoError.invalidSize(AUTHENTICATION_TAG_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Restore an AuthenticationTag from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): AuthenticationTag {\n return new AuthenticationTag(new Uint8Array(data));\n }\n\n /**\n * Restore an AuthenticationTag from a reference to an array of bytes.\n */\n static fromDataRef(data: Uint8Array): AuthenticationTag {\n if (data.length !== AUTHENTICATION_TAG_SIZE) {\n throw CryptoError.invalidSize(AUTHENTICATION_TAG_SIZE, data.length);\n }\n return AuthenticationTag.fromData(data);\n }\n\n /**\n * Create an AuthenticationTag from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): AuthenticationTag {\n return AuthenticationTag.fromData(data);\n }\n\n /**\n * Create an AuthenticationTag from hex string.\n */\n static fromHex(hex: string): AuthenticationTag {\n return AuthenticationTag.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the reference as a byte slice.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw tag bytes as a copy.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n toHex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Compare with another AuthenticationTag.\n */\n equals(other: AuthenticationTag): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `AuthenticationTag(${this.toHex()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (untagged - no CBOR tag for AuthenticationTag)\n // ============================================================================\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n * AuthenticationTag has no CBOR tag - it's serialized as a plain byte string.\n */\n toCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the CBOR binary representation.\n */\n toCborData(): Uint8Array {\n return this.toCbor().toData();\n }\n\n /**\n * Creates an AuthenticationTag from CBOR.\n */\n static fromCbor(cbor: Cbor): AuthenticationTag {\n const data = expectBytes(cbor);\n return AuthenticationTag.fromDataRef(data);\n }\n\n /**\n * Creates an AuthenticationTag from CBOR binary data.\n */\n static fromCborData(data: Uint8Array): AuthenticationTag {\n const cbor = decodeCbor(data);\n return AuthenticationTag.fromCbor(cbor);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Encrypted message with ChaCha20-Poly1305 AEAD\n *\n * A secure encrypted message using IETF ChaCha20-Poly1305 authenticated\n * encryption.\n *\n * `EncryptedMessage` represents data that has been encrypted using a symmetric\n * key with the ChaCha20-Poly1305 AEAD (Authenticated Encryption with\n * Associated Data) construction as specified in [RFC-8439](https://datatracker.ietf.org/doc/html/rfc8439).\n *\n * An `EncryptedMessage` contains:\n * - `ciphertext`: The encrypted data (same length as the original plaintext)\n * - `aad`: Additional Authenticated Data that is not encrypted but is\n * authenticated (optional)\n * - `nonce`: A 12-byte number used once for this specific encryption operation\n * - `auth`: A 16-byte authentication tag that verifies the integrity of the\n * message\n *\n * The `aad` field is often used to include the `Digest` of the plaintext,\n * which allows verification of the plaintext after decryption and preserves\n * the unique identity of the data when used with structures like Gordian\n * Envelope.\n *\n * # CBOR Serialization\n *\n * `EncryptedMessage` is serialized to CBOR with tag 40002.\n *\n * CDDL:\n * ```cddl\n * EncryptedMessage =\n * #6.40002([ ciphertext: bstr, nonce: bstr, auth: bstr, ? aad: bstr ])\n * ```\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), an `EncryptedMessage` is\n * represented with the type \"encrypted\".\n *\n * Ported from bc-components-rust/src/symmetric/encrypted_message.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectArray,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { ENCRYPTED as TAG_ENCRYPTED } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { Nonce } from \"../nonce.js\";\nimport { Digest } from \"../digest.js\";\nimport { AuthenticationTag } from \"./authentication-tag.js\";\nimport { bytesToHex } from \"../utils.js\";\n\nexport class EncryptedMessage\n implements CborTaggedEncodable, CborTaggedDecodable<EncryptedMessage>, UREncodable\n{\n private readonly _ciphertext: Uint8Array;\n private readonly _aad: Uint8Array;\n private readonly _nonce: Nonce;\n private readonly _auth: AuthenticationTag;\n\n private constructor(\n ciphertext: Uint8Array,\n aad: Uint8Array,\n nonce: Nonce,\n auth: AuthenticationTag,\n ) {\n this._ciphertext = new Uint8Array(ciphertext);\n this._aad = new Uint8Array(aad);\n this._nonce = nonce;\n this._auth = auth;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Restores an EncryptedMessage from its components.\n */\n static new(\n ciphertext: Uint8Array,\n aad: Uint8Array,\n nonce: Nonce,\n auth: Uint8Array | AuthenticationTag,\n ): EncryptedMessage {\n const authTag = auth instanceof AuthenticationTag ? auth : AuthenticationTag.fromData(auth);\n return new EncryptedMessage(ciphertext, aad, nonce, authTag);\n }\n\n /**\n * Create an EncryptedMessage from components (legacy alias).\n */\n static from(\n nonce: Nonce,\n ciphertext: Uint8Array,\n tag: AuthenticationTag,\n aad?: Uint8Array,\n ): EncryptedMessage {\n return new EncryptedMessage(ciphertext, aad ?? new Uint8Array(0), nonce, tag);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns a reference to the ciphertext data.\n */\n ciphertext(): Uint8Array {\n return this._ciphertext;\n }\n\n /**\n * Returns a reference to the additional authenticated data (AAD).\n */\n aad(): Uint8Array {\n return this._aad;\n }\n\n /**\n * Returns a reference to the nonce value used for encryption.\n */\n nonce(): Nonce {\n return this._nonce;\n }\n\n /**\n * Returns a reference to the authentication tag value used for encryption.\n */\n authenticationTag(): AuthenticationTag {\n return this._auth;\n }\n\n /**\n * Returns a CBOR representation in the AAD field, if it exists.\n */\n aadCbor(): Cbor | null {\n if (this._aad.length === 0) {\n return null;\n }\n try {\n return decodeCbor(this._aad);\n } catch {\n return null;\n }\n }\n\n /**\n * Returns a Digest instance if the AAD data can be parsed as CBOR.\n */\n aadDigest(): Digest | null {\n const aadCbor = this.aadCbor();\n if (aadCbor === null) {\n return null;\n }\n try {\n return Digest.fromTaggedCbor(aadCbor);\n } catch {\n return null;\n }\n }\n\n /**\n * Returns true if the AAD data can be parsed as a Digest.\n */\n hasDigest(): boolean {\n return this.aadDigest() !== null;\n }\n\n /**\n * Compare with another EncryptedMessage.\n */\n equals(other: EncryptedMessage): boolean {\n if (this._ciphertext.length !== other._ciphertext.length) return false;\n for (let i = 0; i < this._ciphertext.length; i++) {\n if (this._ciphertext[i] !== other._ciphertext[i]) return false;\n }\n if (this._aad.length !== other._aad.length) return false;\n for (let i = 0; i < this._aad.length; i++) {\n if (this._aad[i] !== other._aad[i]) return false;\n }\n return this._nonce.equals(other._nonce) && this._auth.equals(other._auth);\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `EncryptedMessage(ciphertext: ${bytesToHex(this._ciphertext).substring(0, 16)}..., nonce: ${this._nonce.toHex()}, auth: ${this._auth.toHex()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with EncryptedMessage.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_ENCRYPTED.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as an array).\n * Array format: [ciphertext, nonce, auth, ?aad]\n */\n untaggedCbor(): Cbor {\n const elements: Cbor[] = [\n toByteString(this._ciphertext),\n toByteString(this._nonce.data()),\n toByteString(this._auth.data()),\n ];\n\n if (this._aad.length > 0) {\n elements.push(toByteString(this._aad));\n }\n\n return cbor(elements);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an EncryptedMessage by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): EncryptedMessage {\n const elements = expectArray(cborValue);\n\n if (elements.length < 3) {\n throw new Error(\"EncryptedMessage must have at least 3 elements\");\n }\n\n const ciphertext = expectBytes(elements[0]);\n const nonceData = expectBytes(elements[1]);\n const nonce = Nonce.fromDataRef(nonceData);\n const authData = expectBytes(elements[2]);\n const auth = AuthenticationTag.fromDataRef(authData);\n const aad = elements.length > 3 ? expectBytes(elements[3]) : new Uint8Array(0);\n\n return EncryptedMessage.new(ciphertext, aad, nonce, auth);\n }\n\n /**\n * Creates an EncryptedMessage by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): EncryptedMessage {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): EncryptedMessage {\n // Create a dummy instance for accessing instance methods\n const dummy = new EncryptedMessage(\n new Uint8Array(0),\n new Uint8Array(0),\n Nonce.new(),\n AuthenticationTag.fromData(new Uint8Array(16)),\n );\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): EncryptedMessage {\n const cborValue = decodeCbor(data);\n return EncryptedMessage.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): EncryptedMessage {\n const cborValue = decodeCbor(data);\n const dummy = new EncryptedMessage(\n new Uint8Array(0),\n new Uint8Array(0),\n Nonce.new(),\n AuthenticationTag.fromData(new Uint8Array(16)),\n );\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the EncryptedMessage.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"encrypted\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an EncryptedMessage from a UR.\n */\n static fromUR(ur: UR): EncryptedMessage {\n ur.checkType(\"encrypted\");\n const dummy = new EncryptedMessage(\n new Uint8Array(0),\n new Uint8Array(0),\n Nonce.new(),\n AuthenticationTag.fromData(new Uint8Array(16)),\n );\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an EncryptedMessage from a UR string.\n */\n static fromURString(urString: string): EncryptedMessage {\n const ur = UR.fromURString(urString);\n return EncryptedMessage.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Symmetric key for ChaCha20-Poly1305 AEAD encryption (32 bytes)\n *\n * A symmetric encryption key used for both encryption and decryption.\n *\n * `SymmetricKey` is a 32-byte cryptographic key used with ChaCha20-Poly1305\n * AEAD (Authenticated Encryption with Associated Data) encryption. This\n * implementation follows the IETF ChaCha20-Poly1305 specification as defined\n * in [RFC-8439](https://datatracker.ietf.org/doc/html/rfc8439).\n *\n * Symmetric encryption uses the same key for both encryption and decryption,\n * unlike asymmetric encryption where different keys are used for each\n * operation.\n *\n * # CBOR Serialization\n *\n * `SymmetricKey` is serialized to CBOR with tag 40023.\n *\n * Ported from bc-components-rust/src/symmetric/symmetric_key.rs\n */\n\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\nimport {\n aeadChaCha20Poly1305EncryptWithAad,\n aeadChaCha20Poly1305DecryptWithAad,\n} from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { SYMMETRIC_KEY as TAG_SYMMETRIC_KEY } from \"@bcts/tags\";\nimport { UR } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\nimport { Nonce } from \"../nonce.js\";\nimport { EncryptedMessage } from \"./encrypted-message.js\";\n\nconst SYMMETRIC_KEY_SIZE = 32;\n\nexport class SymmetricKey implements CborTaggedEncodable, CborTaggedDecodable<SymmetricKey> {\n static readonly SYMMETRIC_KEY_SIZE = SYMMETRIC_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== SYMMETRIC_KEY_SIZE) {\n throw CryptoError.invalidSize(SYMMETRIC_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new random symmetric key.\n */\n static new(): SymmetricKey {\n return SymmetricKey.random();\n }\n\n /**\n * Create a new symmetric key from data.\n */\n static fromData(data: Uint8Array): SymmetricKey {\n return new SymmetricKey(new Uint8Array(data));\n }\n\n /**\n * Create a new symmetric key from data (validates length).\n */\n static fromDataRef(data: Uint8Array): SymmetricKey {\n if (data.length !== SYMMETRIC_KEY_SIZE) {\n throw CryptoError.invalidSize(SYMMETRIC_KEY_SIZE, data.length);\n }\n return SymmetricKey.fromData(data);\n }\n\n /**\n * Create a SymmetricKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): SymmetricKey {\n return SymmetricKey.fromData(data);\n }\n\n /**\n * Create a SymmetricKey from hex string.\n */\n static fromHex(hex: string): SymmetricKey {\n return SymmetricKey.fromData(hexToBytes(hex));\n }\n\n /**\n * Generate a random symmetric key.\n */\n static random(): SymmetricKey {\n const rng = new SecureRandomNumberGenerator();\n return SymmetricKey.randomUsing(rng);\n }\n\n /**\n * Generate a random symmetric key using provided RNG.\n */\n static randomUsing(rng: SecureRandomNumberGenerator): SymmetricKey {\n return new SymmetricKey(rng.randomData(SYMMETRIC_KEY_SIZE));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get the data of the symmetric key.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the data of the symmetric key as a byte slice.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get a copy of the raw key bytes.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Compare with another SymmetricKey.\n */\n equals(other: SymmetricKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `SymmetricKey(${this.hex().substring(0, 8)}...)`;\n }\n\n // ============================================================================\n // Encryption/Decryption\n // ============================================================================\n\n /**\n * Encrypt the given plaintext with this key, and the given additional\n * authenticated data and nonce.\n */\n encrypt(plaintext: Uint8Array, aad?: Uint8Array, nonce?: Nonce): EncryptedMessage {\n const effectiveNonce = nonce ?? Nonce.new();\n const effectiveAad = aad ?? new Uint8Array(0);\n\n const [ciphertext, authTag] = aeadChaCha20Poly1305EncryptWithAad(\n plaintext,\n this._data,\n effectiveNonce.data(),\n effectiveAad,\n );\n\n return EncryptedMessage.new(ciphertext, effectiveAad, effectiveNonce, authTag);\n }\n\n /**\n * Decrypt the given encrypted message with this key.\n */\n decrypt(message: EncryptedMessage): Uint8Array {\n return aeadChaCha20Poly1305DecryptWithAad(\n message.ciphertext(),\n this._data,\n message.nonce().data(),\n message.aad(),\n message.authenticationTag().data(),\n );\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with SymmetricKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SYMMETRIC_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a SymmetricKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): SymmetricKey {\n const data = expectBytes(cbor);\n return SymmetricKey.fromDataRef(data);\n }\n\n /**\n * Creates a SymmetricKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): SymmetricKey {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): SymmetricKey {\n const instance = new SymmetricKey(new Uint8Array(SYMMETRIC_KEY_SIZE));\n return instance.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): SymmetricKey {\n const cbor = decodeCbor(data);\n return SymmetricKey.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): SymmetricKey {\n const cbor = decodeCbor(data);\n const bytes = expectBytes(cbor);\n return SymmetricKey.fromDataRef(bytes);\n }\n\n // ============================================================================\n // UR (Uniform Resource) Serialization\n // ============================================================================\n\n /**\n * Get the UR type for symmetric keys.\n */\n static readonly UR_TYPE = \"crypto-key\";\n\n /**\n * Returns the UR representation of the symmetric key.\n */\n ur(): UR {\n return UR.new(SymmetricKey.UR_TYPE, this.taggedCbor());\n }\n\n /**\n * Returns the UR string representation of the symmetric key.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a SymmetricKey from a UR.\n */\n static fromUR(ur: UR): SymmetricKey {\n ur.checkType(SymmetricKey.UR_TYPE);\n return SymmetricKey.fromTaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a SymmetricKey from a UR string.\n */\n static fromURString(urString: string): SymmetricKey {\n const ur = UR.fromURString(urString);\n return SymmetricKey.fromUR(ur);\n }\n\n /**\n * Alias for fromURString for Rust API compatibility.\n */\n static fromUrString(urString: string): SymmetricKey {\n return SymmetricKey.fromURString(urString);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * X25519 private key for ECDH key exchange (32 bytes seed)\n *\n * X25519 is an elliptic-curve Diffie-Hellman key exchange protocol based on\n * Curve25519 as defined in RFC 7748. It allows two parties to establish a\n * shared secret key over an insecure channel.\n *\n * Key features of X25519:\n * - High security (128-bit security level)\n * - High performance\n * - Small key sizes (32 bytes)\n * - Protection against various side-channel attacks\n *\n * # CBOR Serialization\n *\n * `X25519PrivateKey` is serialized to CBOR with tag 40010.\n *\n * ```\n * #6.40010(h'<32-byte-private-key>')\n * ```\n *\n * Ported from bc-components-rust/src/x25519/x25519_private_key.rs\n */\n\nimport { SecureRandomNumberGenerator, type RandomNumberGenerator } from \"@bcts/rand\";\nimport {\n X25519_PRIVATE_KEY_SIZE,\n x25519PublicKeyFromPrivateKey,\n x25519SharedKey,\n deriveAgreementPrivateKey,\n} from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { X25519_PRIVATE_KEY as TAG_X25519_PRIVATE_KEY } from \"@bcts/tags\";\nimport { CryptoError } from \"../error.js\";\nimport { X25519PublicKey } from \"./x25519-public-key.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\n\nexport class X25519PrivateKey\n implements CborTaggedEncodable, CborTaggedDecodable<X25519PrivateKey>, UREncodable\n{\n static readonly KEY_SIZE = X25519_PRIVATE_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n private _publicKey?: X25519PublicKey;\n\n private constructor(data: Uint8Array) {\n if (data.length !== X25519_PRIVATE_KEY_SIZE) {\n throw CryptoError.invalidSize(X25519_PRIVATE_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Generate a new random X25519PrivateKey.\n */\n static new(): X25519PrivateKey {\n return X25519PrivateKey.random();\n }\n\n /**\n * Generate a new random X25519PrivateKey.\n */\n static random(): X25519PrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return X25519PrivateKey.newUsing(rng);\n }\n\n /**\n * Generate a new random X25519PrivateKey using provided RNG.\n */\n static newUsing(rng: RandomNumberGenerator): X25519PrivateKey {\n return new X25519PrivateKey(rng.randomData(X25519_PRIVATE_KEY_SIZE));\n }\n\n /**\n * Generate a new random X25519PrivateKey and corresponding X25519PublicKey.\n */\n static keypair(): [X25519PrivateKey, X25519PublicKey] {\n const privateKey = X25519PrivateKey.new();\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Generate a new random X25519PrivateKey and corresponding X25519PublicKey\n * using the given random number generator.\n */\n static keypairUsing(rng: RandomNumberGenerator): [X25519PrivateKey, X25519PublicKey] {\n const privateKey = X25519PrivateKey.newUsing(rng);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Derive an X25519PrivateKey from the given key material.\n *\n * @param keyMaterial - The key material to derive from\n * @returns A new X25519PrivateKey derived from the key material\n */\n static deriveFromKeyMaterial(keyMaterial: Uint8Array): X25519PrivateKey {\n return new X25519PrivateKey(deriveAgreementPrivateKey(keyMaterial));\n }\n\n /**\n * Restore an X25519PrivateKey from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): X25519PrivateKey {\n return new X25519PrivateKey(new Uint8Array(data));\n }\n\n /**\n * Restore an X25519PrivateKey from a reference to an array of bytes.\n * Validates the length.\n */\n static fromDataRef(data: Uint8Array): X25519PrivateKey {\n if (data.length !== X25519_PRIVATE_KEY_SIZE) {\n throw CryptoError.invalidSize(X25519_PRIVATE_KEY_SIZE, data.length);\n }\n return X25519PrivateKey.fromData(data);\n }\n\n /**\n * Create an X25519PrivateKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): X25519PrivateKey {\n return X25519PrivateKey.fromData(data);\n }\n\n /**\n * Restore an X25519PrivateKey from a hex string.\n */\n static fromHex(hex: string): X25519PrivateKey {\n return X25519PrivateKey.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw private key bytes (copy).\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Get the X25519PublicKey corresponding to this X25519PrivateKey.\n */\n publicKey(): X25519PublicKey {\n if (this._publicKey === undefined) {\n const publicKeyBytes = x25519PublicKeyFromPrivateKey(this._data);\n this._publicKey = X25519PublicKey.fromData(publicKeyBytes);\n }\n return this._publicKey;\n }\n\n /**\n * Derive a shared symmetric key from this X25519PrivateKey and the given\n * X25519PublicKey.\n *\n * @param publicKey - The other party's public key\n * @returns A SymmetricKey derived from the shared secret\n */\n sharedKeyWith(publicKey: X25519PublicKey): SymmetricKey {\n const shared = x25519SharedKey(this._data, publicKey.data());\n return SymmetricKey.fromData(shared);\n }\n\n /**\n * Perform ECDH key agreement with a public key (legacy method).\n *\n * @deprecated Use sharedKeyWith() instead which returns a SymmetricKey\n */\n sharedSecret(publicKey: X25519PublicKey): Uint8Array {\n try {\n const shared = x25519SharedKey(this._data, publicKey.data());\n return new Uint8Array(shared);\n } catch (e: unknown) {\n throw CryptoError.cryptoOperation(`ECDH key agreement failed: ${String(e)}`);\n }\n }\n\n /**\n * Compare with another X25519PrivateKey.\n */\n equals(other: X25519PrivateKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `X25519PrivateKey(${this.toHex().substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with X25519PrivateKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_X25519_PRIVATE_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an X25519PrivateKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): X25519PrivateKey {\n const data = expectBytes(cbor);\n return X25519PrivateKey.fromDataRef(data);\n }\n\n /**\n * Creates an X25519PrivateKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): X25519PrivateKey {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): X25519PrivateKey {\n const dummy = new X25519PrivateKey(new Uint8Array(X25519_PRIVATE_KEY_SIZE));\n return dummy.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): X25519PrivateKey {\n const cbor = decodeCbor(data);\n return X25519PrivateKey.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): X25519PrivateKey {\n const cbor = decodeCbor(data);\n const dummy = new X25519PrivateKey(new Uint8Array(X25519_PRIVATE_KEY_SIZE));\n return dummy.fromUntaggedCbor(cbor);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the X25519PrivateKey.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n const name = TAG_X25519_PRIVATE_KEY.name;\n if (name === undefined) {\n throw new Error(\"X25519_PRIVATE_KEY tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an X25519PrivateKey from a UR.\n */\n static fromUR(ur: UR): X25519PrivateKey {\n const name = TAG_X25519_PRIVATE_KEY.name;\n if (name === undefined) {\n throw new Error(\"X25519_PRIVATE_KEY tag name is undefined\");\n }\n ur.checkType(name);\n const dummy = new X25519PrivateKey(new Uint8Array(X25519_PRIVATE_KEY_SIZE));\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an X25519PrivateKey from a UR string.\n */\n static fromURString(urString: string): X25519PrivateKey {\n const ur = UR.fromURString(urString);\n return X25519PrivateKey.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Ed25519 public key for EdDSA signature verification (32 bytes)\n * Ported from bc-components-rust/src/ed25519_public_key.rs\n */\n\nimport { ED25519_PUBLIC_KEY_SIZE, ED25519_SIGNATURE_SIZE, ed25519Verify } from \"@bcts/crypto\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\n\nexport class Ed25519PublicKey {\n private readonly data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== ED25519_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(ED25519_PUBLIC_KEY_SIZE, data.length);\n }\n this.data = new Uint8Array(data);\n }\n\n /**\n * Create an Ed25519PublicKey from raw bytes\n */\n static from(data: Uint8Array): Ed25519PublicKey {\n return new Ed25519PublicKey(new Uint8Array(data));\n }\n\n /**\n * Create an Ed25519PublicKey from hex string\n */\n static fromHex(hex: string): Ed25519PublicKey {\n return new Ed25519PublicKey(hexToBytes(hex));\n }\n\n /**\n * Get the raw public key bytes\n */\n toData(): Uint8Array {\n return new Uint8Array(this.data);\n }\n\n /**\n * Get hex string representation\n */\n toHex(): string {\n return bytesToHex(this.data);\n }\n\n /**\n * Get base64 representation\n */\n toBase64(): string {\n return toBase64(this.data);\n }\n\n /**\n * Verify a signature using Ed25519\n */\n verify(message: Uint8Array, signature: Uint8Array): boolean {\n try {\n if (signature.length !== ED25519_SIGNATURE_SIZE) {\n throw CryptoError.invalidSize(ED25519_SIGNATURE_SIZE, signature.length);\n }\n return ed25519Verify(this.data, message, signature);\n } catch (e) {\n throw CryptoError.cryptoOperation(`Ed25519 verification failed: ${String(e)}`);\n }\n }\n\n /**\n * Compare with another Ed25519PublicKey\n */\n equals(other: Ed25519PublicKey): boolean {\n if (this.data.length !== other.data.length) return false;\n for (let i = 0; i < this.data.length; i++) {\n if (this.data[i] !== other.data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation\n */\n toString(): string {\n return `Ed25519PublicKey(${this.toHex().substring(0, 16)}...)`;\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Ed25519 private key for EdDSA signatures (32 bytes seed)\n * Ported from bc-components-rust/src/ed25519_private_key.rs\n */\n\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\nimport {\n ED25519_PRIVATE_KEY_SIZE,\n ed25519PublicKeyFromPrivateKey,\n ed25519Sign,\n} from \"@bcts/crypto\";\nimport { CryptoError } from \"../error.js\";\nimport { Ed25519PublicKey } from \"./ed25519-public-key.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\n\nexport class Ed25519PrivateKey {\n private readonly seed: Uint8Array;\n private _publicKey?: Ed25519PublicKey;\n\n private constructor(seed: Uint8Array) {\n if (seed.length !== ED25519_PRIVATE_KEY_SIZE) {\n throw CryptoError.invalidSize(ED25519_PRIVATE_KEY_SIZE, seed.length);\n }\n this.seed = new Uint8Array(seed);\n }\n\n /**\n * Create an Ed25519PrivateKey from seed (32 bytes)\n */\n static from(seed: Uint8Array): Ed25519PrivateKey {\n return new Ed25519PrivateKey(new Uint8Array(seed));\n }\n\n /**\n * Create an Ed25519PrivateKey from hex string (64 hex characters)\n */\n static fromHex(hex: string): Ed25519PrivateKey {\n return new Ed25519PrivateKey(hexToBytes(hex));\n }\n\n /**\n * Generate a random Ed25519PrivateKey\n */\n static random(): Ed25519PrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return new Ed25519PrivateKey(rng.randomData(ED25519_PRIVATE_KEY_SIZE));\n }\n\n /**\n * Generate a random Ed25519PrivateKey using provided RNG\n */\n static randomUsing(rng: SecureRandomNumberGenerator): Ed25519PrivateKey {\n return new Ed25519PrivateKey(rng.randomData(ED25519_PRIVATE_KEY_SIZE));\n }\n\n /**\n * Get the raw seed bytes (32 bytes)\n */\n toData(): Uint8Array {\n return new Uint8Array(this.seed);\n }\n\n /**\n * Get hex string representation of the seed\n */\n toHex(): string {\n return bytesToHex(this.seed);\n }\n\n /**\n * Get base64 representation of the seed\n */\n toBase64(): string {\n return toBase64(this.seed);\n }\n\n /**\n * Derive the corresponding public key\n */\n publicKey(): Ed25519PublicKey {\n if (this._publicKey === undefined) {\n const publicKeyBytes = ed25519PublicKeyFromPrivateKey(this.seed);\n this._publicKey = Ed25519PublicKey.from(publicKeyBytes);\n }\n return this._publicKey;\n }\n\n /**\n * Sign a message using Ed25519\n */\n sign(message: Uint8Array): Uint8Array {\n try {\n const signature = ed25519Sign(this.seed, message);\n return new Uint8Array(signature);\n } catch (e) {\n throw CryptoError.cryptoOperation(`Ed25519 signing failed: ${String(e)}`);\n }\n }\n\n /**\n * Compare with another Ed25519PrivateKey\n */\n equals(other: Ed25519PrivateKey): boolean {\n if (this.seed.length !== other.seed.length) return false;\n for (let i = 0; i < this.seed.length; i++) {\n if (this.seed[i] !== other.seed[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation\n */\n toString(): string {\n return `Ed25519PrivateKey(${this.toHex().substring(0, 16)}...)`;\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Sr25519PublicKey - Public key for Schnorr signatures over Ristretto25519\n *\n * SR25519 is the signature scheme used by Polkadot/Substrate.\n * It is based on Schnorr signatures over the Ristretto group.\n *\n * Note: SR25519 uses the SigningPublicKey CBOR tag (40022) with discriminator 3.\n *\n * Ported from bc-components-rust/src/sr25519/sr25519_public_key.rs\n */\n\nimport * as sr25519 from \"@scure/sr25519\";\nimport { SR25519_PUBLIC_KEY_SIZE, SR25519_DEFAULT_CONTEXT } from \"./sr25519-private-key.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * Sr25519PublicKey - Public key for Schnorr signatures over Ristretto25519.\n *\n * This is the signature scheme used by Polkadot/Substrate.\n */\nexport class Sr25519PublicKey {\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== SR25519_PUBLIC_KEY_SIZE) {\n throw new Error(\n `Sr25519PublicKey must be ${SR25519_PUBLIC_KEY_SIZE} bytes, got ${data.length}`,\n );\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an Sr25519 public key from raw bytes.\n */\n static from(data: Uint8Array): Sr25519PublicKey {\n return new Sr25519PublicKey(data);\n }\n\n /**\n * Create an Sr25519 public key from a hex string.\n */\n static fromHex(hex: string): Sr25519PublicKey {\n const matches = hex.match(/.{1,2}/g);\n if (matches === null) {\n throw new Error(\"Invalid hex string\");\n }\n const data = new Uint8Array(matches.map((byte) => parseInt(byte, 16)));\n return Sr25519PublicKey.from(data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the raw key bytes.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the raw key bytes (alias for toData).\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns the hex representation of the key.\n */\n toHex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Verify a signature using the default \"substrate\" context.\n *\n * @param signature - The 64-byte signature\n * @param message - The message that was signed\n * @returns true if the signature is valid\n */\n verify(signature: Uint8Array, message: Uint8Array): boolean {\n return this.verifyWithContext(signature, message, SR25519_DEFAULT_CONTEXT);\n }\n\n /**\n * Verify a signature using a custom context.\n *\n * Note: The @scure/sr25519 library uses a hardcoded \"substrate\" context.\n * Custom context is accepted for API compatibility but only signatures created\n * with \"substrate\" context will verify correctly.\n *\n * @param signature - The 64-byte signature\n * @param message - The message that was signed\n * @param _context - The signing context (only \"substrate\" is supported)\n * @returns true if the signature is valid\n */\n verifyWithContext(signature: Uint8Array, message: Uint8Array, _context: Uint8Array): boolean {\n try {\n // Note: @scure/sr25519 verify() uses hardcoded \"substrate\" context\n // Arguments: verify(message, signature, publicKey)\n return sr25519.verify(message, signature, this._data);\n } catch {\n return false;\n }\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another Sr25519PublicKey.\n */\n equals(other: Sr25519PublicKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `Sr25519PublicKey(${hex.substring(0, 16)}...)`;\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Sr25519PrivateKey - Schnorr signatures over Ristretto25519\n *\n * SR25519 is the signature scheme used by Polkadot/Substrate.\n * It is based on Schnorr signatures over the Ristretto group.\n *\n * Key sizes:\n * - Private key (seed): 32 bytes\n * - Public key: 32 bytes\n * - Signature: 64 bytes\n *\n * Note: SR25519 uses the SigningPrivateKey CBOR tag (40021) with discriminator 3.\n *\n * Ported from bc-components-rust/src/sr25519/sr25519_private_key.rs\n */\n\nimport * as sr25519 from \"@scure/sr25519\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\nimport { blake2b } from \"@noble/hashes/blake2.js\";\nimport { Sr25519PublicKey } from \"./sr25519-public-key.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/** Size of SR25519 private key (seed) in bytes */\nexport const SR25519_PRIVATE_KEY_SIZE = 32;\n\n/** Size of SR25519 public key in bytes */\nexport const SR25519_PUBLIC_KEY_SIZE = 32;\n\n/** Size of SR25519 signature in bytes */\nexport const SR25519_SIGNATURE_SIZE = 64;\n\n/** Default signing context (Substrate/Polkadot compatible) */\nexport const SR25519_DEFAULT_CONTEXT = new TextEncoder().encode(\"substrate\");\n\n/**\n * Sr25519PrivateKey - Private key for Schnorr signatures over Ristretto25519.\n *\n * This is the signature scheme used by Polkadot/Substrate.\n */\nexport class Sr25519PrivateKey {\n private readonly _seed: Uint8Array;\n private _cachedPublicKey?: Sr25519PublicKey;\n\n private constructor(seed: Uint8Array) {\n if (seed.length !== SR25519_PRIVATE_KEY_SIZE) {\n throw new Error(\n `Sr25519PrivateKey seed must be ${SR25519_PRIVATE_KEY_SIZE} bytes, got ${seed.length}`,\n );\n }\n this._seed = new Uint8Array(seed);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new random Sr25519 private key.\n */\n static random(): Sr25519PrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return Sr25519PrivateKey.randomUsing(rng);\n }\n\n /**\n * Create a new random Sr25519 private key using the provided RNG.\n */\n static randomUsing(rng: RandomNumberGenerator): Sr25519PrivateKey {\n const seed = rng.randomData(SR25519_PRIVATE_KEY_SIZE);\n return new Sr25519PrivateKey(seed);\n }\n\n /**\n * Create an Sr25519 private key from a 32-byte seed.\n */\n static fromSeed(seed: Uint8Array): Sr25519PrivateKey {\n return new Sr25519PrivateKey(seed);\n }\n\n /**\n * Create an Sr25519 private key from raw data.\n * Alias for fromSeed.\n */\n static from(data: Uint8Array): Sr25519PrivateKey {\n return Sr25519PrivateKey.fromSeed(data);\n }\n\n /**\n * Create an Sr25519 private key from a hex string.\n */\n static fromHex(hex: string): Sr25519PrivateKey {\n const matches = hex.match(/.{1,2}/g);\n if (matches === null) {\n throw new Error(\"Invalid hex string\");\n }\n const data = new Uint8Array(matches.map((byte) => parseInt(byte, 16)));\n return Sr25519PrivateKey.fromSeed(data);\n }\n\n /**\n * Derive an Sr25519 private key from arbitrary key material using BLAKE2b.\n *\n * @param keyMaterial - Arbitrary bytes to derive the key from\n * @returns A new Sr25519 private key\n */\n static deriveFromKeyMaterial(keyMaterial: Uint8Array): Sr25519PrivateKey {\n // Use BLAKE2b to derive a 32-byte seed from arbitrary key material\n const seed = blake2b(keyMaterial, { dkLen: SR25519_PRIVATE_KEY_SIZE });\n return new Sr25519PrivateKey(seed);\n }\n\n /**\n * Generate a keypair and return both private and public keys.\n *\n * @returns Tuple of [privateKey, publicKey]\n */\n static keypair(): [Sr25519PrivateKey, Sr25519PublicKey] {\n const privateKey = Sr25519PrivateKey.random();\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Generate a keypair using the provided RNG.\n *\n * @param rng - Random number generator\n * @returns Tuple of [privateKey, publicKey]\n */\n static keypairUsing(rng: RandomNumberGenerator): [Sr25519PrivateKey, Sr25519PublicKey] {\n const privateKey = Sr25519PrivateKey.randomUsing(rng);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the raw seed bytes.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._seed);\n }\n\n /**\n * Returns the raw seed bytes (alias for toData).\n */\n asBytes(): Uint8Array {\n return this._seed;\n }\n\n /**\n * Returns the hex representation of the seed.\n */\n toHex(): string {\n return bytesToHex(this._seed);\n }\n\n /**\n * Derives the corresponding public key.\n */\n publicKey(): Sr25519PublicKey {\n if (this._cachedPublicKey === undefined) {\n const secretKey = sr25519.secretFromSeed(this._seed);\n const pubKeyBytes = sr25519.getPublicKey(secretKey);\n this._cachedPublicKey = Sr25519PublicKey.from(pubKeyBytes);\n }\n return this._cachedPublicKey;\n }\n\n /**\n * Sign a message using the default \"substrate\" context.\n *\n * @param message - The message to sign\n * @returns 64-byte signature\n */\n sign(message: Uint8Array): Uint8Array {\n return this.signWithContext(message, SR25519_DEFAULT_CONTEXT);\n }\n\n /**\n * Sign a message using a custom context.\n *\n * Note: The @scure/sr25519 library uses a hardcoded \"substrate\" context.\n * Custom context is accepted for API compatibility but only \"substrate\" context\n * will produce signatures verifiable by this library.\n *\n * @param message - The message to sign\n * @param _context - The signing context (only \"substrate\" is supported)\n * @returns 64-byte signature\n */\n signWithContext(message: Uint8Array, _context: Uint8Array): Uint8Array {\n const secretKey = sr25519.secretFromSeed(this._seed);\n // Note: @scure/sr25519 sign() uses hardcoded \"substrate\" context\n // Arguments: sign(secretKey, message, random?)\n return sr25519.sign(secretKey, message);\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another Sr25519PrivateKey.\n */\n equals(other: Sr25519PrivateKey): boolean {\n if (this._seed.length !== other._seed.length) return false;\n for (let i = 0; i < this._seed.length; i++) {\n if (this._seed[i] !== other._seed[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation (truncated for security).\n */\n toString(): string {\n const hex = bytesToHex(this._seed);\n return `Sr25519PrivateKey(${hex.substring(0, 8)}...)`;\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Base traits for elliptic curve keys\n *\n * This module defines the base interfaces for all elliptic curve keys,\n * matching the Rust trait hierarchy:\n * - `ECKeyBase` - Base trait for all EC keys (data, hex, fromHex, fromDataRef)\n * - `ECKey` - Keys that can derive a public key (publicKey)\n * - `ECPublicKeyBase` - Public keys that can provide uncompressed form\n *\n * Ported from bc-components-rust/src/ec_key/ec_key_base.rs\n * and bc-components-rust/src/ec_key/ec_public_key_base.rs\n */\n\nimport type { ECPublicKey } from \"./ec-public-key.js\";\nimport type { ECUncompressedPublicKey } from \"./ec-uncompressed-public-key.js\";\n\n/**\n * A base interface for all elliptic curve keys.\n *\n * This interface defines common functionality for all elliptic curve keys,\n * including both private and public keys. It provides methods for key\n * construction from binary data and hexadecimal strings, as well as conversion\n * to hexadecimal format.\n *\n * All EC key types have a fixed size depending on their specific type:\n * - EC private keys: 32 bytes\n * - EC compressed public keys: 33 bytes\n * - EC uncompressed public keys: 65 bytes\n * - Schnorr public keys: 32 bytes\n */\nexport interface ECKeyBase {\n /**\n * Returns the key's binary data.\n */\n data(): Uint8Array;\n\n /**\n * Returns the key as a hexadecimal string.\n */\n hex(): string;\n}\n\n/**\n * Type guard to check if an object implements ECKeyBase.\n */\nexport function isECKeyBase(obj: unknown): obj is ECKeyBase {\n if (obj === null || typeof obj !== \"object\") return false;\n const candidate = obj as ECKeyBase;\n return typeof candidate.data === \"function\" && typeof candidate.hex === \"function\";\n}\n\n/**\n * An interface for elliptic curve keys that can derive a public key.\n *\n * This interface extends `ECKeyBase` to provide a method for deriving\n * the corresponding compressed public key. It is implemented by both\n * private keys (where it generates the public key) and public keys\n * (where it may return self or convert between formats).\n */\nexport interface ECKey extends ECKeyBase {\n /**\n * Returns the compressed public key corresponding to this key.\n */\n publicKey(): ECPublicKey;\n}\n\n/**\n * Type guard to check if an object implements ECKey.\n */\nexport function isECKey(obj: unknown): obj is ECKey {\n if (!isECKeyBase(obj)) return false;\n const candidate = obj as ECKey;\n return typeof candidate.publicKey === \"function\";\n}\n\n/**\n * An interface for elliptic curve public keys that can provide their\n * uncompressed form.\n *\n * This interface extends `ECKey` to provide a method for obtaining the\n * uncompressed representation of a public key. Elliptic curve public keys can\n * be represented in both compressed (33 bytes) and uncompressed (65 bytes)\n * formats:\n *\n * - Compressed format: Uses a single byte prefix (0x02 or 0x03) followed by\n * the x-coordinate (32 bytes), with the prefix indicating the parity of the\n * y-coordinate.\n *\n * - Uncompressed format: Uses a byte prefix (0x04) followed by both x and y\n * coordinates (32 bytes each), for a total of 65 bytes.\n *\n * The compressed format is more space-efficient and is recommended for most\n * applications, but some legacy systems require the uncompressed format.\n */\nexport interface ECPublicKeyBase extends ECKey {\n /**\n * Returns the uncompressed public key representation.\n */\n uncompressedPublicKey(): ECUncompressedPublicKey;\n}\n\n/**\n * Type guard to check if an object implements ECPublicKeyBase.\n */\nexport function isECPublicKeyBase(obj: unknown): obj is ECPublicKeyBase {\n if (!isECKey(obj)) return false;\n const candidate = obj as ECPublicKeyBase;\n return typeof candidate.uncompressedPublicKey === \"function\";\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * EC uncompressed public key for ECDSA (secp256k1, 65 bytes)\n *\n * An `ECUncompressedPublicKey` is a 65-byte uncompressed representation of a\n * public key on the secp256k1 curve. The first byte is 0x04 (uncompressed prefix),\n * followed by the 32-byte x-coordinate and 32-byte y-coordinate.\n *\n * While compressed public keys (33 bytes) are preferred for space efficiency,\n * uncompressed keys are sometimes needed for compatibility with legacy systems.\n *\n * # CBOR Serialization\n *\n * `ECUncompressedPublicKey` is serialized to CBOR with tags 40306 (or legacy 306).\n *\n * The format is a map:\n * ```\n * #6.40306({\n * 3: h'<65-byte-uncompressed-public-key>' // key data\n * })\n * ```\n *\n * Ported from bc-components-rust/src/ec_key/ec_uncompressed_public_key.rs\n */\n\nimport { ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE, ecdsaCompressPublicKey } from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectMap,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { EC_KEY as TAG_EC_KEY, EC_KEY_V1 as TAG_EC_KEY_V1 } from \"@bcts/tags\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\nimport type { ECKeyBase } from \"./ec-key-base.js\";\n\nexport class ECUncompressedPublicKey\n implements\n ECKeyBase,\n CborTaggedEncodable,\n CborTaggedDecodable<ECUncompressedPublicKey>,\n UREncodable\n{\n static readonly KEY_SIZE = ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Restore an ECUncompressedPublicKey from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): ECUncompressedPublicKey {\n return new ECUncompressedPublicKey(new Uint8Array(data));\n }\n\n /**\n * Restore an ECUncompressedPublicKey from a reference to an array of bytes.\n * Validates the length.\n */\n static fromDataRef(data: Uint8Array): ECUncompressedPublicKey {\n if (data.length !== ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE, data.length);\n }\n return ECUncompressedPublicKey.fromData(data);\n }\n\n /**\n * Create an ECUncompressedPublicKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): ECUncompressedPublicKey {\n return ECUncompressedPublicKey.fromData(data);\n }\n\n /**\n * Restore an ECUncompressedPublicKey from a hex string.\n */\n static fromHex(hex: string): ECUncompressedPublicKey {\n return ECUncompressedPublicKey.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw public key bytes (copy).\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Convert to compressed public key format.\n * Note: Returns the compressed bytes. To get ECPublicKey, use the ec-public-key module.\n */\n compressedData(): Uint8Array {\n return ecdsaCompressPublicKey(this._data);\n }\n\n /**\n * Compare with another ECUncompressedPublicKey.\n */\n equals(other: ECUncompressedPublicKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `ECUncompressedPublicKey(${this.toHex().substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with ECUncompressedPublicKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_EC_KEY.value, TAG_EC_KEY_V1.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: { 3: h'<65-byte-key>' }\n */\n untaggedCbor(): Cbor {\n const map = new Map<number, unknown>();\n map.set(3, toByteString(this._data));\n return cbor(map);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an ECUncompressedPublicKey by decoding it from untagged CBOR.\n *\n * Format: { 3: h'<65-byte-key>' }\n */\n fromUntaggedCbor(cborValue: Cbor): ECUncompressedPublicKey {\n const map = expectMap(cborValue);\n\n // Check that key 2 is not present (would indicate private key)\n const isPrivate = map.get<number, boolean>(2);\n if (isPrivate === true) {\n throw new Error(\"Expected ECUncompressedPublicKey but found private key\");\n }\n\n // Get key data from key 3\n // CborMap.extract() returns native types (Uint8Array for byte strings)\n const keyData = map.extract<number, Uint8Array>(3);\n if (keyData === undefined || keyData.length === 0) {\n throw new Error(\"ECUncompressedPublicKey CBOR must have key 3 (data)\");\n }\n\n return ECUncompressedPublicKey.fromDataRef(keyData);\n }\n\n /**\n * Creates an ECUncompressedPublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): ECUncompressedPublicKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): ECUncompressedPublicKey {\n const dummy = new ECUncompressedPublicKey(new Uint8Array(ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE));\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): ECUncompressedPublicKey {\n const cborValue = decodeCbor(data);\n return ECUncompressedPublicKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): ECUncompressedPublicKey {\n const cborValue = decodeCbor(data);\n const dummy = new ECUncompressedPublicKey(new Uint8Array(ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE));\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the ECUncompressedPublicKey.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n const name = TAG_EC_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_EC_KEY.name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an ECUncompressedPublicKey from a UR.\n */\n static fromUR(ur: UR): ECUncompressedPublicKey {\n const name = TAG_EC_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_EC_KEY.name is undefined\");\n }\n ur.checkType(name);\n const dummy = new ECUncompressedPublicKey(new Uint8Array(ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE));\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an ECUncompressedPublicKey from a UR string.\n */\n static fromURString(urString: string): ECUncompressedPublicKey {\n const ur = UR.fromURString(urString);\n return ECUncompressedPublicKey.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * EC compressed public key for ECDSA verification (secp256k1, 33 bytes)\n *\n * An `ECPublicKey` is a 33-byte compressed representation of a public key on\n * the secp256k1 curve. The first byte is a prefix (0x02 or 0x03) that\n * indicates the parity of the y-coordinate, followed by the 32-byte\n * x-coordinate.\n *\n * These public keys are used to:\n * - Verify ECDSA signatures\n * - Identify the owner of a private key without revealing the private key\n *\n * # CBOR Serialization\n *\n * `ECPublicKey` is serialized to CBOR with tags 40306 (or legacy 306).\n *\n * The format is a map:\n * ```\n * #6.40306({\n * 3: h'<33-byte-public-key>' // key data (no key 2 means public key)\n * })\n * ```\n *\n * Ported from bc-components-rust/src/ec_key/ec_public_key.rs\n */\n\nimport { ECDSA_PUBLIC_KEY_SIZE, ecdsaVerify, ecdsaDecompressPublicKey } from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectMap,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { EC_KEY as TAG_EC_KEY, EC_KEY_V1 as TAG_EC_KEY_V1 } from \"@bcts/tags\";\nimport { CryptoError } from \"../error.js\";\nimport { ECUncompressedPublicKey } from \"./ec-uncompressed-public-key.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\nimport type { ECPublicKeyBase } from \"./ec-key-base.js\";\n\nexport class ECPublicKey\n implements ECPublicKeyBase, CborTaggedEncodable, CborTaggedDecodable<ECPublicKey>, UREncodable\n{\n static readonly KEY_SIZE = ECDSA_PUBLIC_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== ECDSA_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(ECDSA_PUBLIC_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Restore an ECPublicKey from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): ECPublicKey {\n return new ECPublicKey(new Uint8Array(data));\n }\n\n /**\n * Restore an ECPublicKey from a reference to an array of bytes.\n * Validates the length.\n */\n static fromDataRef(data: Uint8Array): ECPublicKey {\n if (data.length !== ECDSA_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(ECDSA_PUBLIC_KEY_SIZE, data.length);\n }\n return ECPublicKey.fromData(data);\n }\n\n /**\n * Create an ECPublicKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): ECPublicKey {\n return ECPublicKey.fromData(data);\n }\n\n /**\n * Restore an ECPublicKey from a hex string.\n */\n static fromHex(hex: string): ECPublicKey {\n return ECPublicKey.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw public key bytes (copy).\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Returns the compressed public key (self).\n *\n * This method implements the ECKey interface. Since ECPublicKey is already\n * a compressed public key, this returns itself.\n */\n publicKey(): ECPublicKey {\n return this;\n }\n\n /**\n * Convert this compressed public key to uncompressed format.\n */\n uncompressedPublicKey(): ECUncompressedPublicKey {\n const uncompressed = ecdsaDecompressPublicKey(this._data);\n return ECUncompressedPublicKey.fromData(uncompressed);\n }\n\n /**\n * Verify an ECDSA signature.\n *\n * @param signature - The 64-byte signature to verify\n * @param message - The message that was signed\n * @returns true if the signature is valid\n */\n verify(signature: Uint8Array, message: Uint8Array): boolean {\n try {\n return ecdsaVerify(this._data, signature, message);\n } catch {\n return false;\n }\n }\n\n /**\n * Compare with another ECPublicKey.\n */\n equals(other: ECPublicKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `ECPublicKey(${this.toHex().substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with ECPublicKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_EC_KEY.value, TAG_EC_KEY_V1.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: { 3: h'<33-byte-key>' }\n * Note: No key 2 indicates this is a public key\n */\n untaggedCbor(): Cbor {\n const map = new Map<number, unknown>();\n map.set(3, toByteString(this._data));\n return cbor(map);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an ECPublicKey by decoding it from untagged CBOR.\n *\n * Format: { 3: h'<33-byte-key>' }\n */\n fromUntaggedCbor(cborValue: Cbor): ECPublicKey {\n const map = expectMap(cborValue);\n\n // Check that key 2 is not present (would indicate private key)\n const isPrivate = map.get<number, boolean>(2);\n if (isPrivate === true) {\n throw new Error(\"Expected ECPublicKey but found private key (key 2 is true)\");\n }\n\n // Get key data from key 3\n // CborMap.extract() returns native types (Uint8Array for byte strings)\n const keyData = map.extract<number, Uint8Array>(3);\n if (keyData === undefined || keyData.length === 0) {\n throw new Error(\"ECPublicKey CBOR must have key 3 (data)\");\n }\n\n return ECPublicKey.fromDataRef(keyData);\n }\n\n /**\n * Creates an ECPublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): ECPublicKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): ECPublicKey {\n const dummy = new ECPublicKey(new Uint8Array(ECDSA_PUBLIC_KEY_SIZE));\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): ECPublicKey {\n const cborValue = decodeCbor(data);\n return ECPublicKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): ECPublicKey {\n const cborValue = decodeCbor(data);\n const dummy = new ECPublicKey(new Uint8Array(ECDSA_PUBLIC_KEY_SIZE));\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the ECPublicKey.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n const name = TAG_EC_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_EC_KEY.name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an ECPublicKey from a UR.\n */\n static fromUR(ur: UR): ECPublicKey {\n const name = TAG_EC_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_EC_KEY.name is undefined\");\n }\n ur.checkType(name);\n const dummy = new ECPublicKey(new Uint8Array(ECDSA_PUBLIC_KEY_SIZE));\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an ECPublicKey from a UR string.\n */\n static fromURString(urString: string): ECPublicKey {\n const ur = UR.fromURString(urString);\n return ECPublicKey.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Schnorr (x-only) public key for BIP-340 signatures (secp256k1, 32 bytes)\n *\n * A `SchnorrPublicKey` is a 32-byte \"x-only\" public key used with the BIP-340\n * Schnorr signature scheme. Unlike compressed ECDSA public keys (33 bytes)\n * that include a prefix byte indicating the parity of the y-coordinate,\n * Schnorr public keys only contain the x-coordinate of the elliptic curve\n * point.\n *\n * Schnorr signatures offer several advantages over traditional ECDSA\n * signatures:\n * - Linearity: Enables key and signature aggregation\n * - Non-malleability: Prevents third parties from modifying signatures\n * - Smaller size: Signatures are 64 bytes vs 70-72 bytes for ECDSA\n * - Better privacy: Makes different multisig policies indistinguishable\n *\n * Schnorr signatures were introduced to Bitcoin via the Taproot upgrade\n * (BIP-340).\n *\n * Note: SchnorrPublicKey does not have CBOR serialization in the Rust\n * implementation, so we keep it simple here.\n *\n * Ported from bc-components-rust/src/ec_key/schnorr_public_key.rs\n */\n\nimport { SCHNORR_PUBLIC_KEY_SIZE, schnorrVerify } from \"@bcts/crypto\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\nimport type { ECKeyBase } from \"./ec-key-base.js\";\n\nexport class SchnorrPublicKey implements ECKeyBase {\n static readonly KEY_SIZE = SCHNORR_PUBLIC_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== SCHNORR_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(SCHNORR_PUBLIC_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Restore a SchnorrPublicKey from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): SchnorrPublicKey {\n return new SchnorrPublicKey(new Uint8Array(data));\n }\n\n /**\n * Restore a SchnorrPublicKey from a reference to an array of bytes.\n * Validates the length.\n */\n static fromDataRef(data: Uint8Array): SchnorrPublicKey {\n if (data.length !== SCHNORR_PUBLIC_KEY_SIZE) {\n throw CryptoError.invalidSize(SCHNORR_PUBLIC_KEY_SIZE, data.length);\n }\n return SchnorrPublicKey.fromData(data);\n }\n\n /**\n * Create a SchnorrPublicKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): SchnorrPublicKey {\n return SchnorrPublicKey.fromData(data);\n }\n\n /**\n * Restore a SchnorrPublicKey from a hex string.\n */\n static fromHex(hex: string): SchnorrPublicKey {\n return SchnorrPublicKey.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw public key bytes (copy).\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Verify a Schnorr signature (BIP-340).\n *\n * @param signature - The 64-byte signature to verify\n * @param message - The message that was signed\n * @returns true if the signature is valid\n */\n schnorrVerify(signature: Uint8Array, message: Uint8Array): boolean {\n try {\n return schnorrVerify(this._data, signature, message);\n } catch {\n return false;\n }\n }\n\n /**\n * Compare with another SchnorrPublicKey.\n */\n equals(other: SchnorrPublicKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `SchnorrPublicKey(${this.toHex().substring(0, 16)}...)`;\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * EC private key for ECDSA and Schnorr signatures (secp256k1, 32 bytes)\n *\n * An `ECPrivateKey` is a 32-byte secret value that can be used to:\n * - Generate its corresponding public key\n * - Sign messages using the ECDSA signature scheme\n * - Sign messages using the Schnorr signature scheme (BIP-340)\n *\n * These keys use the secp256k1 curve, which is the same curve used in Bitcoin\n * and other cryptocurrencies.\n *\n * # CBOR Serialization\n *\n * `ECPrivateKey` is serialized to CBOR with tags 40306 (or legacy 306).\n *\n * The format is a map:\n * ```\n * #6.40306({\n * 2: true, // indicates private key\n * 3: h'<32-byte-private-key>' // key data\n * })\n * ```\n *\n * Ported from bc-components-rust/src/ec_key/ec_private_key.rs\n */\n\nimport { SecureRandomNumberGenerator, type RandomNumberGenerator } from \"@bcts/rand\";\nimport {\n ECDSA_PRIVATE_KEY_SIZE,\n ecdsaPublicKeyFromPrivateKey,\n ecdsaDerivePrivateKey,\n ecdsaSign,\n schnorrPublicKeyFromPrivateKey,\n schnorrSign,\n schnorrSignUsing,\n} from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectMap,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { EC_KEY as TAG_EC_KEY, EC_KEY_V1 as TAG_EC_KEY_V1 } from \"@bcts/tags\";\nimport { CryptoError } from \"../error.js\";\nimport { ECPublicKey } from \"./ec-public-key.js\";\nimport { SchnorrPublicKey } from \"./schnorr-public-key.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"../utils.js\";\nimport type { ECKey } from \"./ec-key-base.js\";\n\nexport class ECPrivateKey\n implements ECKey, CborTaggedEncodable, CborTaggedDecodable<ECPrivateKey>, UREncodable\n{\n static readonly KEY_SIZE = ECDSA_PRIVATE_KEY_SIZE;\n\n private readonly _data: Uint8Array;\n private _publicKey?: ECPublicKey;\n private _schnorrPublicKey?: SchnorrPublicKey;\n\n private constructor(data: Uint8Array) {\n if (data.length !== ECDSA_PRIVATE_KEY_SIZE) {\n throw CryptoError.invalidSize(ECDSA_PRIVATE_KEY_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Generate a new random ECPrivateKey.\n */\n static new(): ECPrivateKey {\n return ECPrivateKey.random();\n }\n\n /**\n * Generate a new random ECPrivateKey.\n */\n static random(): ECPrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return ECPrivateKey.newUsing(rng);\n }\n\n /**\n * Generate a new random ECPrivateKey using provided RNG.\n */\n static newUsing(rng: RandomNumberGenerator): ECPrivateKey {\n return new ECPrivateKey(rng.randomData(ECDSA_PRIVATE_KEY_SIZE));\n }\n\n /**\n * Generate a new random ECPrivateKey and corresponding ECPublicKey.\n */\n static keypair(): [ECPrivateKey, ECPublicKey] {\n const privateKey = ECPrivateKey.new();\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Generate a new random ECPrivateKey and corresponding ECPublicKey\n * using the given random number generator.\n */\n static keypairUsing(rng: RandomNumberGenerator): [ECPrivateKey, ECPublicKey] {\n const privateKey = ECPrivateKey.newUsing(rng);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Derive an ECPrivateKey from the given key material.\n *\n * @param keyMaterial - The key material to derive from\n * @returns A new ECPrivateKey derived from the key material\n */\n static deriveFromKeyMaterial(keyMaterial: Uint8Array): ECPrivateKey {\n return new ECPrivateKey(ecdsaDerivePrivateKey(keyMaterial));\n }\n\n /**\n * Restore an ECPrivateKey from a fixed-size array of bytes.\n */\n static fromData(data: Uint8Array): ECPrivateKey {\n return new ECPrivateKey(new Uint8Array(data));\n }\n\n /**\n * Restore an ECPrivateKey from a reference to an array of bytes.\n * Validates the length.\n */\n static fromDataRef(data: Uint8Array): ECPrivateKey {\n if (data.length !== ECDSA_PRIVATE_KEY_SIZE) {\n throw CryptoError.invalidSize(ECDSA_PRIVATE_KEY_SIZE, data.length);\n }\n return ECPrivateKey.fromData(data);\n }\n\n /**\n * Create an ECPrivateKey from raw bytes (legacy alias).\n */\n static from(data: Uint8Array): ECPrivateKey {\n return ECPrivateKey.fromData(data);\n }\n\n /**\n * Restore an ECPrivateKey from a hex string.\n */\n static fromHex(hex: string): ECPrivateKey {\n return ECPrivateKey.fromData(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get a reference to the fixed-size array of bytes.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get the raw private key bytes (copy).\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Get the ECPublicKey (compressed) corresponding to this ECPrivateKey.\n */\n publicKey(): ECPublicKey {\n if (this._publicKey === undefined) {\n const publicKeyBytes = ecdsaPublicKeyFromPrivateKey(this._data);\n this._publicKey = ECPublicKey.fromData(publicKeyBytes);\n }\n return this._publicKey;\n }\n\n /**\n * Get the SchnorrPublicKey (x-only) corresponding to this ECPrivateKey.\n */\n schnorrPublicKey(): SchnorrPublicKey {\n if (this._schnorrPublicKey === undefined) {\n const publicKeyBytes = schnorrPublicKeyFromPrivateKey(this._data);\n this._schnorrPublicKey = SchnorrPublicKey.fromData(publicKeyBytes);\n }\n return this._schnorrPublicKey;\n }\n\n /**\n * Sign a message using ECDSA.\n *\n * @param message - The message to sign\n * @returns A 64-byte signature\n */\n ecdsaSign(message: Uint8Array): Uint8Array {\n try {\n return ecdsaSign(this._data, message);\n } catch (e) {\n throw CryptoError.cryptoOperation(`ECDSA signing failed: ${String(e)}`);\n }\n }\n\n /**\n * Sign a message using Schnorr signature (BIP-340).\n *\n * @param message - The message to sign\n * @returns A 64-byte signature\n */\n schnorrSign(message: Uint8Array): Uint8Array {\n try {\n return schnorrSign(this._data, message);\n } catch (e) {\n throw CryptoError.cryptoOperation(`Schnorr signing failed: ${String(e)}`);\n }\n }\n\n /**\n * Sign a message using Schnorr signature with custom RNG.\n *\n * @param message - The message to sign\n * @param rng - Random number generator for auxiliary randomness\n * @returns A 64-byte signature\n */\n schnorrSignUsing(message: Uint8Array, rng: RandomNumberGenerator): Uint8Array {\n try {\n return schnorrSignUsing(this._data, message, rng);\n } catch (e) {\n throw CryptoError.cryptoOperation(`Schnorr signing failed: ${String(e)}`);\n }\n }\n\n /**\n * Compare with another ECPrivateKey.\n */\n equals(other: ECPrivateKey): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `ECPrivateKey(${this.toHex().substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with ECPrivateKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_EC_KEY.value, TAG_EC_KEY_V1.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: { 2: true, 3: h'<32-byte-key>' }\n */\n untaggedCbor(): Cbor {\n const map = new Map<number, unknown>();\n map.set(2, true);\n map.set(3, toByteString(this._data));\n return cbor(map);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an ECPrivateKey by decoding it from untagged CBOR.\n *\n * Format: { 2: true, 3: h'<32-byte-key>' }\n */\n fromUntaggedCbor(cborValue: Cbor): ECPrivateKey {\n const map = expectMap(cborValue);\n\n // Check for key 2 (isPrivate = true)\n const isPrivate = map.get<number, boolean>(2);\n if (isPrivate !== true) {\n throw new Error(\"ECPrivateKey CBOR must have key 2 set to true\");\n }\n\n // Get key data from key 3\n // CborMap.extract() returns native types (Uint8Array for byte strings)\n const keyData = map.extract<number, Uint8Array>(3);\n if (keyData === undefined || keyData.length === 0) {\n throw new Error(\"ECPrivateKey CBOR must have key 3 (data)\");\n }\n\n return ECPrivateKey.fromDataRef(keyData);\n }\n\n /**\n * Creates an ECPrivateKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): ECPrivateKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): ECPrivateKey {\n const dummy = new ECPrivateKey(new Uint8Array(ECDSA_PRIVATE_KEY_SIZE));\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): ECPrivateKey {\n const cborValue = decodeCbor(data);\n return ECPrivateKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): ECPrivateKey {\n const cborValue = decodeCbor(data);\n const dummy = new ECPrivateKey(new Uint8Array(ECDSA_PRIVATE_KEY_SIZE));\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the ECPrivateKey.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n const name = TAG_EC_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_EC_KEY.name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an ECPrivateKey from a UR.\n */\n static fromUR(ur: UR): ECPrivateKey {\n const name = TAG_EC_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_EC_KEY.name is undefined\");\n }\n ur.checkType(name);\n const dummy = new ECPrivateKey(new Uint8Array(ECDSA_PRIVATE_KEY_SIZE));\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an ECPrivateKey from a UR string.\n */\n static fromURString(urString: string): ECPrivateKey {\n const ur = UR.fromURString(urString);\n return ECPrivateKey.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * MLDSA Security Level - ML-DSA (Module-Lattice-Based Digital Signature Algorithm)\n *\n * ML-DSA is a post-quantum digital signature algorithm standardized by NIST.\n * It provides three security levels corresponding to different NIST security categories.\n *\n * Security levels:\n * - MLDSA44: NIST Level 2 (equivalent to AES-128)\n * - MLDSA65: NIST Level 3 (equivalent to AES-192)\n * - MLDSA87: NIST Level 5 (equivalent to AES-256)\n *\n * Ported from bc-components-rust/src/mldsa/mldsa_level.rs\n */\n\nimport { ml_dsa44, ml_dsa65, ml_dsa87 } from \"@noble/post-quantum/ml-dsa.js\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\n\n/**\n * ML-DSA security levels.\n *\n * The numeric values correspond to NIST security levels:\n * - 2: NIST Level 2 (MLDSA44)\n * - 3: NIST Level 3 (MLDSA65)\n * - 5: NIST Level 5 (MLDSA87)\n */\nexport enum MLDSALevel {\n /** NIST Level 2 - AES-128 equivalent security */\n MLDSA44 = 2,\n /** NIST Level 3 - AES-192 equivalent security */\n MLDSA65 = 3,\n /** NIST Level 5 - AES-256 equivalent security */\n MLDSA87 = 5,\n}\n\n/**\n * Key sizes for each ML-DSA security level.\n */\nexport const MLDSA_KEY_SIZES = {\n [MLDSALevel.MLDSA44]: {\n privateKey: 2560,\n publicKey: 1312,\n signature: 2420,\n },\n [MLDSALevel.MLDSA65]: {\n privateKey: 4032,\n publicKey: 1952,\n signature: 3309,\n },\n [MLDSALevel.MLDSA87]: {\n privateKey: 4896,\n publicKey: 2592,\n signature: 4627,\n },\n} as const;\n\n/**\n * Get the private key size for a given ML-DSA level.\n */\nexport function mldsaPrivateKeySize(level: MLDSALevel): number {\n return MLDSA_KEY_SIZES[level].privateKey;\n}\n\n/**\n * Get the public key size for a given ML-DSA level.\n */\nexport function mldsaPublicKeySize(level: MLDSALevel): number {\n return MLDSA_KEY_SIZES[level].publicKey;\n}\n\n/**\n * Get the signature size for a given ML-DSA level.\n */\nexport function mldsaSignatureSize(level: MLDSALevel): number {\n return MLDSA_KEY_SIZES[level].signature;\n}\n\n/**\n * Convert an ML-DSA level to its string representation.\n */\nexport function mldsaLevelToString(level: MLDSALevel): string {\n switch (level) {\n case MLDSALevel.MLDSA44:\n return \"MLDSA44\";\n case MLDSALevel.MLDSA65:\n return \"MLDSA65\";\n case MLDSALevel.MLDSA87:\n return \"MLDSA87\";\n }\n}\n\n/**\n * Parse an ML-DSA level from its numeric value.\n */\nexport function mldsaLevelFromValue(value: number): MLDSALevel {\n switch (value) {\n case 2:\n return MLDSALevel.MLDSA44;\n case 3:\n return MLDSALevel.MLDSA65;\n case 5:\n return MLDSALevel.MLDSA87;\n default:\n throw new Error(`Invalid MLDSA level value: ${value}`);\n }\n}\n\n/**\n * Internal type for ML-DSA keypair generation result.\n */\nexport interface MLDSAKeypairData {\n publicKey: Uint8Array;\n secretKey: Uint8Array;\n}\n\n/**\n * Generate an ML-DSA keypair for the given security level.\n *\n * @param level - The ML-DSA security level\n * @returns Object containing publicKey and secretKey bytes\n */\nexport function mldsaGenerateKeypair(level: MLDSALevel): MLDSAKeypairData {\n const rng = new SecureRandomNumberGenerator();\n return mldsaGenerateKeypairUsing(level, rng);\n}\n\n/**\n * Generate an ML-DSA keypair using a provided RNG.\n *\n * @param level - The ML-DSA security level\n * @param rng - Random number generator\n * @returns Object containing publicKey and secretKey bytes\n */\nexport function mldsaGenerateKeypairUsing(\n level: MLDSALevel,\n rng: RandomNumberGenerator,\n): MLDSAKeypairData {\n // Generate random seed for keypair generation\n const seed = rng.randomData(32);\n\n switch (level) {\n case MLDSALevel.MLDSA44: {\n const keypair = ml_dsa44.keygen(seed);\n return { publicKey: keypair.publicKey, secretKey: keypair.secretKey };\n }\n case MLDSALevel.MLDSA65: {\n const keypair = ml_dsa65.keygen(seed);\n return { publicKey: keypair.publicKey, secretKey: keypair.secretKey };\n }\n case MLDSALevel.MLDSA87: {\n const keypair = ml_dsa87.keygen(seed);\n return { publicKey: keypair.publicKey, secretKey: keypair.secretKey };\n }\n }\n}\n\n/**\n * Sign a message using ML-DSA.\n *\n * @param level - The ML-DSA security level\n * @param secretKey - The secret key bytes\n * @param message - The message to sign\n * @returns The signature bytes\n */\nexport function mldsaSign(\n level: MLDSALevel,\n secretKey: Uint8Array,\n message: Uint8Array,\n): Uint8Array {\n switch (level) {\n case MLDSALevel.MLDSA44:\n return ml_dsa44.sign(message, secretKey);\n case MLDSALevel.MLDSA65:\n return ml_dsa65.sign(message, secretKey);\n case MLDSALevel.MLDSA87:\n return ml_dsa87.sign(message, secretKey);\n }\n}\n\n/**\n * Verify a signature using ML-DSA.\n *\n * @param level - The ML-DSA security level\n * @param publicKey - The public key bytes\n * @param message - The message that was signed\n * @param signature - The signature to verify\n * @returns True if the signature is valid\n */\nexport function mldsaVerify(\n level: MLDSALevel,\n publicKey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array,\n): boolean {\n try {\n switch (level) {\n case MLDSALevel.MLDSA44:\n return ml_dsa44.verify(signature, message, publicKey);\n case MLDSALevel.MLDSA65:\n return ml_dsa65.verify(signature, message, publicKey);\n case MLDSALevel.MLDSA87:\n return ml_dsa87.verify(signature, message, publicKey);\n }\n } catch {\n return false;\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * MLDSAPublicKey - ML-DSA Public Key for post-quantum signature verification\n *\n * MLDSAPublicKey wraps an ML-DSA public key for verifying signatures.\n * It supports all three security levels (MLDSA44, MLDSA65, MLDSA87).\n *\n * # CBOR Serialization\n *\n * MLDSAPublicKey is serialized with tag 40104:\n * ```\n * #6.40104([level, h'<public-key-bytes>'])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `mldsa-public-key`\n *\n * Ported from bc-components-rust/src/mldsa/mldsa_public_key.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n expectInteger,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { MLDSA_PUBLIC_KEY as TAG_MLDSA_PUBLIC_KEY } from \"@bcts/tags\";\n\nimport {\n MLDSALevel,\n mldsaLevelFromValue,\n mldsaLevelToString,\n mldsaPublicKeySize,\n mldsaVerify,\n} from \"./mldsa-level.js\";\nimport type { MLDSASignature } from \"./mldsa-signature.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * MLDSAPublicKey - Post-quantum signature verification key using ML-DSA.\n */\nexport class MLDSAPublicKey\n implements CborTaggedEncodable, CborTaggedDecodable<MLDSAPublicKey>, UREncodable\n{\n private readonly _level: MLDSALevel;\n private readonly _data: Uint8Array;\n\n private constructor(level: MLDSALevel, data: Uint8Array) {\n const expectedSize = mldsaPublicKeySize(level);\n if (data.length !== expectedSize) {\n throw new Error(\n `MLDSAPublicKey (${mldsaLevelToString(level)}) must be ${expectedSize} bytes, got ${data.length}`,\n );\n }\n this._level = level;\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an MLDSAPublicKey from raw bytes.\n *\n * @param level - The ML-DSA security level\n * @param data - The public key bytes\n */\n static fromBytes(level: MLDSALevel, data: Uint8Array): MLDSAPublicKey {\n return new MLDSAPublicKey(level, data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the security level of this key.\n */\n level(): MLDSALevel {\n return this._level;\n }\n\n /**\n * Returns the raw key bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw key bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the size of the key in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n /**\n * Verify a signature against a message.\n *\n * @param signature - The ML-DSA signature to verify\n * @param message - The message that was signed\n * @returns True if the signature is valid\n */\n verify(signature: MLDSASignature, message: Uint8Array): boolean {\n if (signature.level() !== this._level) {\n return false;\n }\n return mldsaVerify(this._level, this._data, message, signature.asBytes());\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another MLDSAPublicKey.\n */\n equals(other: MLDSAPublicKey): boolean {\n if (this._level !== other._level) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `MLDSAPublicKey(${mldsaLevelToString(this._level)}, ${hex.substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with MLDSAPublicKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_MLDSA_PUBLIC_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [level, key_bytes]\n */\n untaggedCbor(): Cbor {\n return cbor([this._level, this._data]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an MLDSAPublicKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): MLDSAPublicKey {\n const elements = expectArray(cborValue);\n if (elements.length !== 2) {\n throw new Error(`MLDSAPublicKey CBOR must have 2 elements, got ${elements.length}`);\n }\n const levelValue = Number(expectInteger(elements[0]));\n const level = mldsaLevelFromValue(levelValue);\n const data = expectBytes(elements[1]);\n return MLDSAPublicKey.fromBytes(level, data);\n }\n\n /**\n * Creates an MLDSAPublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): MLDSAPublicKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): MLDSAPublicKey {\n // Create a minimal dummy instance for decoding\n const dummyData = new Uint8Array(mldsaPublicKeySize(MLDSALevel.MLDSA44));\n const dummy = new MLDSAPublicKey(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): MLDSAPublicKey {\n const cborValue = decodeCbor(data);\n return MLDSAPublicKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): MLDSAPublicKey {\n const cborValue = decodeCbor(data);\n const dummyData = new Uint8Array(mldsaPublicKeySize(MLDSALevel.MLDSA44));\n const dummy = new MLDSAPublicKey(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_MLDSA_PUBLIC_KEY.name;\n if (name === undefined) {\n throw new Error(\"MLDSA_PUBLIC_KEY tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an MLDSAPublicKey from a UR.\n */\n static fromUR(ur: UR): MLDSAPublicKey {\n if (ur.urTypeStr() !== TAG_MLDSA_PUBLIC_KEY.name) {\n throw new Error(`Expected UR type ${TAG_MLDSA_PUBLIC_KEY.name}, got ${ur.urTypeStr()}`);\n }\n const dummyData = new Uint8Array(mldsaPublicKeySize(MLDSALevel.MLDSA44));\n const dummy = new MLDSAPublicKey(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an MLDSAPublicKey from a UR string.\n */\n static fromURString(urString: string): MLDSAPublicKey {\n const ur = UR.fromURString(urString);\n return MLDSAPublicKey.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * MLDSASignature - ML-DSA Digital Signature\n *\n * MLDSASignature wraps an ML-DSA signature for serialization and verification.\n * It supports all three security levels (MLDSA44, MLDSA65, MLDSA87).\n *\n * # CBOR Serialization\n *\n * MLDSASignature is serialized with tag 40105:\n * ```\n * #6.40105([level, h'<signature-bytes>'])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `mldsa-signature`\n *\n * Ported from bc-components-rust/src/mldsa/mldsa_signature.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n expectInteger,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { MLDSA_SIGNATURE as TAG_MLDSA_SIGNATURE } from \"@bcts/tags\";\n\nimport {\n MLDSALevel,\n mldsaLevelFromValue,\n mldsaLevelToString,\n mldsaSignatureSize,\n} from \"./mldsa-level.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * MLDSASignature - Post-quantum digital signature using ML-DSA.\n */\nexport class MLDSASignature\n implements CborTaggedEncodable, CborTaggedDecodable<MLDSASignature>, UREncodable\n{\n private readonly _level: MLDSALevel;\n private readonly _data: Uint8Array;\n\n private constructor(level: MLDSALevel, data: Uint8Array) {\n const expectedSize = mldsaSignatureSize(level);\n if (data.length !== expectedSize) {\n throw new Error(\n `MLDSASignature (${mldsaLevelToString(level)}) must be ${expectedSize} bytes, got ${data.length}`,\n );\n }\n this._level = level;\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an MLDSASignature from raw bytes.\n *\n * @param level - The ML-DSA security level\n * @param data - The signature bytes\n */\n static fromBytes(level: MLDSALevel, data: Uint8Array): MLDSASignature {\n return new MLDSASignature(level, data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the security level of this signature.\n */\n level(): MLDSALevel {\n return this._level;\n }\n\n /**\n * Returns the raw signature bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw signature bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the size of the signature in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another MLDSASignature.\n */\n equals(other: MLDSASignature): boolean {\n if (this._level !== other._level) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `MLDSASignature(${mldsaLevelToString(this._level)}, ${hex.substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with MLDSASignature.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_MLDSA_SIGNATURE.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [level, signature_bytes]\n */\n untaggedCbor(): Cbor {\n return cbor([this._level, this._data]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an MLDSASignature by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): MLDSASignature {\n const elements = expectArray(cborValue);\n if (elements.length !== 2) {\n throw new Error(`MLDSASignature CBOR must have 2 elements, got ${elements.length}`);\n }\n const levelValue = Number(expectInteger(elements[0]));\n const level = mldsaLevelFromValue(levelValue);\n const data = expectBytes(elements[1]);\n return MLDSASignature.fromBytes(level, data);\n }\n\n /**\n * Creates an MLDSASignature by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): MLDSASignature {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): MLDSASignature {\n // Create a minimal dummy instance for decoding\n const dummyData = new Uint8Array(mldsaSignatureSize(MLDSALevel.MLDSA44));\n const dummy = new MLDSASignature(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): MLDSASignature {\n const cborValue = decodeCbor(data);\n return MLDSASignature.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): MLDSASignature {\n const cborValue = decodeCbor(data);\n const dummyData = new Uint8Array(mldsaSignatureSize(MLDSALevel.MLDSA44));\n const dummy = new MLDSASignature(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_MLDSA_SIGNATURE.name;\n if (name === undefined) {\n throw new Error(\"MLDSA_SIGNATURE tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an MLDSASignature from a UR.\n */\n static fromUR(ur: UR): MLDSASignature {\n if (ur.urTypeStr() !== TAG_MLDSA_SIGNATURE.name) {\n throw new Error(`Expected UR type ${TAG_MLDSA_SIGNATURE.name}, got ${ur.urTypeStr()}`);\n }\n const dummyData = new Uint8Array(mldsaSignatureSize(MLDSALevel.MLDSA44));\n const dummy = new MLDSASignature(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an MLDSASignature from a UR string.\n */\n static fromURString(urString: string): MLDSASignature {\n const ur = UR.fromURString(urString);\n return MLDSASignature.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * MLDSAPrivateKey - ML-DSA Private Key for post-quantum digital signatures\n *\n * MLDSAPrivateKey wraps an ML-DSA secret key for signing messages.\n * It supports all three security levels (MLDSA44, MLDSA65, MLDSA87).\n *\n * # CBOR Serialization\n *\n * MLDSAPrivateKey is serialized with tag 40103:\n * ```\n * #6.40103([level, h'<private-key-bytes>'])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `mldsa-private-key`\n *\n * Ported from bc-components-rust/src/mldsa/mldsa_private_key.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n expectInteger,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { MLDSA_PRIVATE_KEY as TAG_MLDSA_PRIVATE_KEY } from \"@bcts/tags\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\n\nimport {\n MLDSALevel,\n mldsaLevelFromValue,\n mldsaLevelToString,\n mldsaPrivateKeySize,\n mldsaGenerateKeypairUsing,\n mldsaSign,\n} from \"./mldsa-level.js\";\nimport { MLDSAPublicKey } from \"./mldsa-public-key.js\";\nimport { MLDSASignature } from \"./mldsa-signature.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * MLDSAPrivateKey - Post-quantum signing private key using ML-DSA.\n */\nexport class MLDSAPrivateKey\n implements CborTaggedEncodable, CborTaggedDecodable<MLDSAPrivateKey>, UREncodable\n{\n private readonly _level: MLDSALevel;\n private readonly _data: Uint8Array;\n\n private constructor(level: MLDSALevel, data: Uint8Array) {\n const expectedSize = mldsaPrivateKeySize(level);\n if (data.length !== expectedSize) {\n throw new Error(\n `MLDSAPrivateKey (${mldsaLevelToString(level)}) must be ${expectedSize} bytes, got ${data.length}`,\n );\n }\n this._level = level;\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Generate a new random MLDSAPrivateKey with the specified security level.\n *\n * @param level - The ML-DSA security level (default: MLDSA65)\n */\n static new(level: MLDSALevel = MLDSALevel.MLDSA65): MLDSAPrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return MLDSAPrivateKey.newUsing(level, rng);\n }\n\n /**\n * Generate a new random MLDSAPrivateKey using the provided RNG.\n *\n * @param level - The ML-DSA security level\n * @param rng - Random number generator\n */\n static newUsing(level: MLDSALevel, rng: RandomNumberGenerator): MLDSAPrivateKey {\n const keypair = mldsaGenerateKeypairUsing(level, rng);\n return new MLDSAPrivateKey(level, keypair.secretKey);\n }\n\n /**\n * Create an MLDSAPrivateKey from raw bytes.\n *\n * @param level - The ML-DSA security level\n * @param data - The private key bytes\n */\n static fromBytes(level: MLDSALevel, data: Uint8Array): MLDSAPrivateKey {\n return new MLDSAPrivateKey(level, data);\n }\n\n /**\n * Generate a keypair and return both private and public keys.\n *\n * @param level - The ML-DSA security level (default: MLDSA65)\n * @returns Tuple of [privateKey, publicKey]\n */\n static keypair(level: MLDSALevel = MLDSALevel.MLDSA65): [MLDSAPrivateKey, MLDSAPublicKey] {\n const rng = new SecureRandomNumberGenerator();\n return MLDSAPrivateKey.keypairUsing(level, rng);\n }\n\n /**\n * Generate a keypair using the provided RNG.\n *\n * @param level - The ML-DSA security level\n * @param rng - Random number generator\n * @returns Tuple of [privateKey, publicKey]\n */\n static keypairUsing(\n level: MLDSALevel,\n rng: RandomNumberGenerator,\n ): [MLDSAPrivateKey, MLDSAPublicKey] {\n const keypairData = mldsaGenerateKeypairUsing(level, rng);\n const privateKey = new MLDSAPrivateKey(level, keypairData.secretKey);\n const publicKey = MLDSAPublicKey.fromBytes(level, keypairData.publicKey);\n return [privateKey, publicKey];\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the security level of this key.\n */\n level(): MLDSALevel {\n return this._level;\n }\n\n /**\n * Returns the raw key bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw key bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the size of the key in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n /**\n * Sign a message with this private key.\n *\n * @param message - The message to sign\n * @returns The ML-DSA signature\n */\n sign(message: Uint8Array): MLDSASignature {\n const sigBytes = mldsaSign(this._level, this._data, message);\n return MLDSASignature.fromBytes(this._level, sigBytes);\n }\n\n /**\n * Derive the public key from this private key.\n *\n * Note: ML-DSA doesn't have a direct derivation method, so we need to\n * regenerate the keypair from seed. For now, we extract from the secret key\n * structure (the public key is embedded in the secret key for ML-DSA).\n */\n publicKey(): MLDSAPublicKey {\n // In ML-DSA, the public key can be extracted from the secret key\n // The noble library stores (secretKey, publicKey) concatenated\n // For MLDSA44: secretKey = 2560 bytes, publicKey = 1312 bytes\n // For MLDSA65: secretKey = 4032 bytes, publicKey = 1952 bytes\n // For MLDSA87: secretKey = 4896 bytes, publicKey = 2592 bytes\n\n // Actually, noble stores them separately in keygen(), and the secret key\n // doesn't contain the public key. We need to regenerate or cache.\n // For simplicity, we'll generate a new keypair with the same seed.\n // But we don't have the seed... This is a limitation.\n\n // The solution is to either:\n // 1. Store the public key alongside the private key\n // 2. Re-generate from seed (but we don't have it)\n // 3. Use a deterministic derivation\n\n // For now, we'll throw an error and require users to use keypair() instead.\n // This matches the Rust implementation where public_key() uses the internal\n // key structure which may have the public key embedded.\n\n // Actually, looking at the noble implementation, we can't easily extract\n // the public key. The keypair generation is what produces both.\n // So we need to either:\n // a) Store both keys together\n // b) Require users to keep track of both\n\n // For MVP, we'll throw an error suggesting to use keypair()\n throw new Error(\n \"MLDSAPrivateKey.publicKey() is not supported. Use MLDSAPrivateKey.keypair() to generate both keys together.\",\n );\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another MLDSAPrivateKey.\n */\n equals(other: MLDSAPrivateKey): boolean {\n if (this._level !== other._level) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation (truncated for security).\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `MLDSAPrivateKey(${mldsaLevelToString(this._level)}, ${hex.substring(0, 8)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with MLDSAPrivateKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_MLDSA_PRIVATE_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [level, key_bytes]\n */\n untaggedCbor(): Cbor {\n return cbor([this._level, this._data]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an MLDSAPrivateKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): MLDSAPrivateKey {\n const elements = expectArray(cborValue);\n if (elements.length !== 2) {\n throw new Error(`MLDSAPrivateKey CBOR must have 2 elements, got ${elements.length}`);\n }\n const levelValue = Number(expectInteger(elements[0]));\n const level = mldsaLevelFromValue(levelValue);\n const data = expectBytes(elements[1]);\n return MLDSAPrivateKey.fromBytes(level, data);\n }\n\n /**\n * Creates an MLDSAPrivateKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): MLDSAPrivateKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): MLDSAPrivateKey {\n // Create a minimal dummy instance for decoding\n const dummyData = new Uint8Array(mldsaPrivateKeySize(MLDSALevel.MLDSA44));\n const dummy = new MLDSAPrivateKey(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): MLDSAPrivateKey {\n const cborValue = decodeCbor(data);\n return MLDSAPrivateKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): MLDSAPrivateKey {\n const cborValue = decodeCbor(data);\n const dummyData = new Uint8Array(mldsaPrivateKeySize(MLDSALevel.MLDSA44));\n const dummy = new MLDSAPrivateKey(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_MLDSA_PRIVATE_KEY.name;\n if (name === undefined) {\n throw new Error(\"MLDSA_PRIVATE_KEY tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an MLDSAPrivateKey from a UR.\n */\n static fromUR(ur: UR): MLDSAPrivateKey {\n if (ur.urTypeStr() !== TAG_MLDSA_PRIVATE_KEY.name) {\n throw new Error(`Expected UR type ${TAG_MLDSA_PRIVATE_KEY.name}, got ${ur.urTypeStr()}`);\n }\n const dummyData = new Uint8Array(mldsaPrivateKeySize(MLDSALevel.MLDSA44));\n const dummy = new MLDSAPrivateKey(MLDSALevel.MLDSA44, dummyData);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an MLDSAPrivateKey from a UR string.\n */\n static fromURString(urString: string): MLDSAPrivateKey {\n const ur = UR.fromURString(urString);\n return MLDSAPrivateKey.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * A digital signature created with various signature algorithms.\n *\n * `Signature` represents different types of digital signatures.\n * Supports Schnorr, ECDSA, Ed25519, and Sr25519 signatures.\n *\n * Signatures can be serialized to and from CBOR with tag 40020.\n *\n * # CBOR Serialization\n *\n * The CBOR encoding (matching Rust bc-components):\n * - Schnorr: `#6.40020(h'<64-byte-signature>')` (bare byte string)\n * - ECDSA: `#6.40020([1, h'<64-byte-signature>'])`\n * - Ed25519: `#6.40020([2, h'<64-byte-signature>'])`\n * - Sr25519: `#6.40020([3, h'<64-byte-signature>'])`\n *\n * Ported from bc-components-rust/src/signing/signature.rs\n */\n\nimport { ED25519_SIGNATURE_SIZE, ECDSA_SIGNATURE_SIZE, SCHNORR_SIGNATURE_SIZE } from \"@bcts/crypto\";\nimport { SR25519_SIGNATURE_SIZE } from \"../sr25519/sr25519-private-key.js\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectArray,\n expectBytes,\n expectUnsigned,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n isBytes,\n isArray,\n isTagged,\n} from \"@bcts/dcbor\";\nimport { SIGNATURE as TAG_SIGNATURE, MLDSA_SIGNATURE as TAG_MLDSA_SIGNATURE } from \"@bcts/tags\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex, hexToBytes } from \"../utils.js\";\nimport { SignatureScheme, isMldsaScheme } from \"./signature-scheme.js\";\nimport { MLDSASignature } from \"../mldsa/mldsa-signature.js\";\nimport { MLDSALevel } from \"../mldsa/mldsa-level.js\";\nimport { UR } from \"@bcts/uniform-resources\";\n\n/**\n * A digital signature created with various signature algorithms.\n *\n * Currently supports:\n * - Schnorr signatures (64 bytes) - bare byte string in CBOR\n * - ECDSA signatures (64 bytes) - discriminator 1\n * - Ed25519 signatures (64 bytes) - discriminator 2\n * - Sr25519 signatures (64 bytes) - discriminator 3\n * - MLDSA signatures (post-quantum) - tagged CBOR delegating to MLDSASignature\n */\nexport class Signature implements CborTaggedEncodable, CborTaggedDecodable<Signature> {\n private readonly _type: SignatureScheme;\n private readonly _data: Uint8Array;\n private readonly _mldsaSignature: MLDSASignature | undefined;\n\n private constructor(type: SignatureScheme, data: Uint8Array, mldsaSignature?: MLDSASignature) {\n this._type = type;\n this._data = new Uint8Array(data);\n this._mldsaSignature = mldsaSignature;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Creates a Schnorr signature from a 64-byte array.\n *\n * @param data - The 64-byte signature data\n * @returns A new Schnorr signature\n */\n static schnorrFromData(data: Uint8Array): Signature {\n if (data.length !== SCHNORR_SIGNATURE_SIZE) {\n throw CryptoError.invalidSize(SCHNORR_SIGNATURE_SIZE, data.length);\n }\n return new Signature(SignatureScheme.Schnorr, data);\n }\n\n /**\n * Creates a Schnorr signature from a hex string.\n *\n * @param hex - The hex-encoded signature data\n * @returns A new Schnorr signature\n */\n static schnorrFromHex(hex: string): Signature {\n return Signature.schnorrFromData(hexToBytes(hex));\n }\n\n /**\n * Creates an ECDSA signature from a 64-byte array.\n *\n * @param data - The 64-byte signature data\n * @returns A new ECDSA signature\n */\n static ecdsaFromData(data: Uint8Array): Signature {\n if (data.length !== ECDSA_SIGNATURE_SIZE) {\n throw CryptoError.invalidSize(ECDSA_SIGNATURE_SIZE, data.length);\n }\n return new Signature(SignatureScheme.Ecdsa, data);\n }\n\n /**\n * Creates an ECDSA signature from a hex string.\n *\n * @param hex - The hex-encoded signature data\n * @returns A new ECDSA signature\n */\n static ecdsaFromHex(hex: string): Signature {\n return Signature.ecdsaFromData(hexToBytes(hex));\n }\n\n /**\n * Creates an Ed25519 signature from a 64-byte array.\n *\n * @param data - The 64-byte signature data\n * @returns A new Ed25519 signature\n */\n static ed25519FromData(data: Uint8Array): Signature {\n if (data.length !== ED25519_SIGNATURE_SIZE) {\n throw CryptoError.invalidSize(ED25519_SIGNATURE_SIZE, data.length);\n }\n return new Signature(SignatureScheme.Ed25519, data);\n }\n\n /**\n * Creates an Ed25519 signature from a hex string.\n *\n * @param hex - The hex-encoded signature data\n * @returns A new Ed25519 signature\n */\n static ed25519FromHex(hex: string): Signature {\n return Signature.ed25519FromData(hexToBytes(hex));\n }\n\n /**\n * Creates an Sr25519 signature from a 64-byte array.\n *\n * @param data - The 64-byte signature data\n * @returns A new Sr25519 signature\n */\n static sr25519FromData(data: Uint8Array): Signature {\n if (data.length !== SR25519_SIGNATURE_SIZE) {\n throw CryptoError.invalidSize(SR25519_SIGNATURE_SIZE, data.length);\n }\n return new Signature(SignatureScheme.Sr25519, data);\n }\n\n /**\n * Creates an Sr25519 signature from a hex string.\n *\n * @param hex - The hex-encoded signature data\n * @returns A new Sr25519 signature\n */\n static sr25519FromHex(hex: string): Signature {\n return Signature.sr25519FromData(hexToBytes(hex));\n }\n\n /**\n * Creates a Signature from an MLDSASignature.\n *\n * @param sig - The MLDSASignature\n * @returns A new Signature wrapping the MLDSA signature\n */\n static mldsaFromSignature(sig: MLDSASignature): Signature {\n // Determine the SignatureScheme based on the MLDSA level\n let scheme: SignatureScheme;\n switch (sig.level()) {\n case MLDSALevel.MLDSA44:\n scheme = SignatureScheme.MLDSA44;\n break;\n case MLDSALevel.MLDSA65:\n scheme = SignatureScheme.MLDSA65;\n break;\n case MLDSALevel.MLDSA87:\n scheme = SignatureScheme.MLDSA87;\n break;\n default:\n throw new Error(`Unknown MLDSA level: ${sig.level()}`);\n }\n return new Signature(scheme, sig.data(), sig);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the signature scheme used to create this signature.\n */\n scheme(): SignatureScheme {\n return this._type;\n }\n\n /**\n * Returns a human-readable string identifying the signature type.\n * @returns A string like \"Ed25519\", \"Schnorr\", \"ECDSA\", \"Sr25519\", \"MLDSA-44\", etc.\n */\n signatureType(): string {\n switch (this._type) {\n case SignatureScheme.Ed25519:\n return \"Ed25519\";\n case SignatureScheme.Schnorr:\n return \"Schnorr\";\n case SignatureScheme.Ecdsa:\n return \"Ecdsa\";\n case SignatureScheme.Sr25519:\n return \"Sr25519\";\n case SignatureScheme.MLDSA44:\n return \"MLDSA-44\";\n case SignatureScheme.MLDSA65:\n return \"MLDSA-65\";\n case SignatureScheme.MLDSA87:\n return \"MLDSA-87\";\n case SignatureScheme.SshEd25519:\n return \"SshEd25519\";\n case SignatureScheme.SshDsa:\n return \"SshDsa\";\n case SignatureScheme.SshEcdsaP256:\n return \"SshEcdsaP256\";\n case SignatureScheme.SshEcdsaP384:\n return \"SshEcdsaP384\";\n default:\n return this._type;\n }\n }\n\n /**\n * Returns the raw signature data.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns the Schnorr signature data if this is a Schnorr signature.\n *\n * @returns The 64-byte signature data if this is a Schnorr signature, null otherwise\n */\n toSchnorr(): Uint8Array | null {\n if (this._type === SignatureScheme.Schnorr) {\n return this._data;\n }\n return null;\n }\n\n /**\n * Checks if this is a Schnorr signature.\n */\n isSchnorr(): boolean {\n return this._type === SignatureScheme.Schnorr;\n }\n\n /**\n * Returns the ECDSA signature data if this is an ECDSA signature.\n *\n * @returns The 64-byte signature data if this is an ECDSA signature, null otherwise\n */\n toEcdsa(): Uint8Array | null {\n if (this._type === SignatureScheme.Ecdsa) {\n return this._data;\n }\n return null;\n }\n\n /**\n * Checks if this is an ECDSA signature.\n */\n isEcdsa(): boolean {\n return this._type === SignatureScheme.Ecdsa;\n }\n\n /**\n * Returns the Ed25519 signature data if this is an Ed25519 signature.\n *\n * @returns The 64-byte signature data if this is an Ed25519 signature, null otherwise\n */\n toEd25519(): Uint8Array | null {\n if (this._type === SignatureScheme.Ed25519) {\n return this._data;\n }\n return null;\n }\n\n /**\n * Checks if this is an Ed25519 signature.\n */\n isEd25519(): boolean {\n return this._type === SignatureScheme.Ed25519;\n }\n\n /**\n * Returns the Sr25519 signature data if this is an Sr25519 signature.\n *\n * @returns The 64-byte signature data if this is an Sr25519 signature, null otherwise\n */\n toSr25519(): Uint8Array | null {\n if (this._type === SignatureScheme.Sr25519) {\n return this._data;\n }\n return null;\n }\n\n /**\n * Checks if this is an Sr25519 signature.\n */\n isSr25519(): boolean {\n return this._type === SignatureScheme.Sr25519;\n }\n\n /**\n * Returns the MLDSASignature if this is an MLDSA signature.\n *\n * @returns The MLDSASignature if this is an MLDSA signature, null otherwise\n */\n toMldsa(): MLDSASignature | null {\n if (isMldsaScheme(this._type) && this._mldsaSignature !== undefined) {\n return this._mldsaSignature;\n }\n return null;\n }\n\n /**\n * Checks if this is an MLDSA signature.\n */\n isMldsa(): boolean {\n return isMldsaScheme(this._type);\n }\n\n /**\n * Get hex string representation of the signature data.\n */\n toHex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Compare with another Signature.\n */\n equals(other: Signature): boolean {\n if (this._type !== other._type) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `Signature(${this._type}, ${this.toHex().substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with Signature.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SIGNATURE.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format (matching Rust bc-components):\n * - Schnorr: h'<64-byte-signature>' (bare byte string)\n * - ECDSA: [1, h'<64-byte-signature>']\n * - Ed25519: [2, h'<64-byte-signature>']\n * - Sr25519: [3, h'<64-byte-signature>']\n */\n untaggedCbor(): Cbor {\n switch (this._type) {\n case SignatureScheme.Schnorr:\n // Rust: CBOR::to_byte_string(data) - bare byte string\n return toByteString(this._data);\n case SignatureScheme.Ecdsa:\n return cbor([1, toByteString(this._data)]);\n case SignatureScheme.Ed25519:\n return cbor([2, toByteString(this._data)]);\n case SignatureScheme.Sr25519:\n return cbor([3, toByteString(this._data)]);\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87: {\n if (this._mldsaSignature === undefined) {\n throw new Error(\"MLDSA signature is missing\");\n }\n // Rust: delegates to MLDSASignature (which produces tagged CBOR)\n return this._mldsaSignature.taggedCbor();\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n throw new Error(`SSH signature scheme ${this._type} is not supported for CBOR encoding`);\n }\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a Signature by decoding it from untagged CBOR.\n *\n * Format (matching Rust bc-components):\n * - h'<64-byte-signature>' (bare byte string) for Schnorr\n * - [1, h'<64-byte-signature>'] for ECDSA\n * - [2, h'<64-byte-signature>'] for Ed25519\n * - [3, h'<64-byte-signature>'] for Sr25519\n */\n fromUntaggedCbor(cborValue: Cbor): Signature {\n // Rust format: Schnorr is a bare byte string\n if (isBytes(cborValue)) {\n const signatureData = expectBytes(cborValue);\n return Signature.schnorrFromData(signatureData);\n }\n\n // Array format for ECDSA, Ed25519, Sr25519\n if (isArray(cborValue)) {\n const elements = expectArray(cborValue);\n\n if (elements.length !== 2) {\n throw new Error(\"Signature array must have 2 elements\");\n }\n\n const discriminator = expectUnsigned(elements[0]);\n const signatureData = expectBytes(elements[1]);\n\n switch (Number(discriminator)) {\n case 1: // ECDSA\n return Signature.ecdsaFromData(signatureData);\n case 2: // Ed25519\n return Signature.ed25519FromData(signatureData);\n case 3: // Sr25519\n return Signature.sr25519FromData(signatureData);\n default:\n throw new Error(`Unknown signature discriminator: ${discriminator}`);\n }\n }\n\n // Tagged format for MLDSA\n if (isTagged(cborValue)) {\n const tagged = cborValue.asTagged();\n if (tagged?.[0].value === TAG_MLDSA_SIGNATURE.value) {\n const mldsaSig = MLDSASignature.fromTaggedCbor(cborValue);\n return Signature.mldsaFromSignature(mldsaSig);\n }\n }\n\n throw new Error(\n \"Signature must be a byte string (Schnorr), array (ECDSA/Ed25519/Sr25519), or tagged MLDSA\",\n );\n }\n\n /**\n * Creates a Signature by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): Signature {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): Signature {\n // Create a dummy instance for accessing instance methods\n const dummy = new Signature(SignatureScheme.Ed25519, new Uint8Array(ED25519_SIGNATURE_SIZE));\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): Signature {\n const cborValue = decodeCbor(data);\n return Signature.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): Signature {\n const cborValue = decodeCbor(data);\n const dummy = new Signature(SignatureScheme.Ed25519, new Uint8Array(ED25519_SIGNATURE_SIZE));\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR (Uniform Resource) Serialization\n // ============================================================================\n\n /**\n * Get the UR type for signatures.\n */\n static readonly UR_TYPE = \"signature\";\n\n /**\n * Returns the UR representation of the signature.\n */\n ur(): UR {\n return UR.new(Signature.UR_TYPE, this.taggedCbor());\n }\n\n /**\n * Returns the UR string representation of the signature.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a Signature from a UR.\n */\n static fromUR(ur: UR): Signature {\n ur.checkType(Signature.UR_TYPE);\n return Signature.fromTaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a Signature from a UR string.\n */\n static fromURString(urString: string): Signature {\n const ur = UR.fromURString(urString);\n return Signature.fromUR(ur);\n }\n\n /**\n * Alias for fromURString for Rust API compatibility.\n */\n static fromUrString(urString: string): Signature {\n return Signature.fromURString(urString);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * A public key used for verifying digital signatures.\n *\n * `SigningPublicKey` is a type representing different types of signing public\n * keys. Supports Schnorr, ECDSA, Ed25519, and SR25519.\n *\n * This type implements the `Verifier` interface, allowing it to verify signatures.\n *\n * # CBOR Serialization\n *\n * `SigningPublicKey` is serialized to CBOR with tag 40022.\n *\n * The CBOR encoding (matching Rust bc-components):\n * - Schnorr: `#6.40022(h'<32-byte-x-only-public-key>')` (bare byte string)\n * - ECDSA: `#6.40022([1, h'<33-byte-compressed-public-key>'])`\n * - Ed25519: `#6.40022([2, h'<32-byte-public-key>'])`\n * - Sr25519: `#6.40022([3, h'<32-byte-public-key>'])`\n *\n * Ported from bc-components-rust/src/signing/signing_public_key.rs\n */\n\nimport { ED25519_PUBLIC_KEY_SIZE } from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectArray,\n expectBytes,\n expectUnsigned,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n isBytes,\n isArray,\n isTagged,\n} from \"@bcts/dcbor\";\nimport {\n SIGNING_PUBLIC_KEY as TAG_SIGNING_PUBLIC_KEY,\n MLDSA_PUBLIC_KEY as TAG_MLDSA_PUBLIC_KEY,\n} from \"@bcts/tags\";\nimport { Ed25519PublicKey } from \"../ed25519/ed25519-public-key.js\";\nimport { Sr25519PublicKey } from \"../sr25519/sr25519-public-key.js\";\nimport { ECPublicKey } from \"../ec-key/ec-public-key.js\";\nimport { SchnorrPublicKey } from \"../ec-key/schnorr-public-key.js\";\nimport { MLDSAPublicKey } from \"../mldsa/mldsa-public-key.js\";\nimport { MLDSALevel } from \"../mldsa/mldsa-level.js\";\nimport { SignatureScheme, isMldsaScheme } from \"./signature-scheme.js\";\nimport type { Signature } from \"./signature.js\";\nimport type { Verifier } from \"./signer.js\";\nimport { Reference, type ReferenceProvider } from \"../reference.js\";\nimport { Digest } from \"../digest.js\";\nimport { UR } from \"@bcts/uniform-resources\";\n\n/**\n * A public key used for verifying digital signatures.\n *\n * Currently supports:\n * - Schnorr public keys (32 bytes, x-only) - bare byte string in CBOR\n * - ECDSA public keys (33 bytes, compressed) - discriminator 1\n * - Ed25519 public keys (32 bytes) - discriminator 2\n * - Sr25519 public keys (32 bytes) - discriminator 3\n * - MLDSA public keys (post-quantum) - tagged CBOR delegating to MLDSAPublicKey\n */\nexport class SigningPublicKey\n implements Verifier, ReferenceProvider, CborTaggedEncodable, CborTaggedDecodable<SigningPublicKey>\n{\n private readonly _type: SignatureScheme;\n private readonly _schnorrKey: SchnorrPublicKey | undefined;\n private readonly _ecdsaKey: ECPublicKey | undefined;\n private readonly _ed25519Key: Ed25519PublicKey | undefined;\n private readonly _sr25519Key: Sr25519PublicKey | undefined;\n private readonly _mldsaKey: MLDSAPublicKey | undefined;\n\n private constructor(\n type: SignatureScheme,\n schnorrKey?: SchnorrPublicKey,\n ecdsaKey?: ECPublicKey,\n ed25519Key?: Ed25519PublicKey,\n sr25519Key?: Sr25519PublicKey,\n mldsaKey?: MLDSAPublicKey,\n ) {\n this._type = type;\n this._schnorrKey = schnorrKey;\n this._ecdsaKey = ecdsaKey;\n this._ed25519Key = ed25519Key;\n this._sr25519Key = sr25519Key;\n this._mldsaKey = mldsaKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Creates a new signing public key from a Schnorr (x-only) public key.\n *\n * @param key - A SchnorrPublicKey\n * @returns A new signing public key containing the Schnorr key\n */\n static fromSchnorr(key: SchnorrPublicKey): SigningPublicKey {\n return new SigningPublicKey(\n SignatureScheme.Schnorr,\n key,\n undefined,\n undefined,\n undefined,\n undefined,\n );\n }\n\n /**\n * Creates a new signing public key from an ECDSA (compressed) public key.\n *\n * @param key - An ECPublicKey\n * @returns A new signing public key containing the ECDSA key\n */\n static fromEcdsa(key: ECPublicKey): SigningPublicKey {\n return new SigningPublicKey(\n SignatureScheme.Ecdsa,\n undefined,\n key,\n undefined,\n undefined,\n undefined,\n );\n }\n\n /**\n * Creates a new signing public key from an Ed25519 public key.\n *\n * @param key - An Ed25519 public key\n * @returns A new signing public key containing the Ed25519 key\n */\n static fromEd25519(key: Ed25519PublicKey): SigningPublicKey {\n return new SigningPublicKey(\n SignatureScheme.Ed25519,\n undefined,\n undefined,\n key,\n undefined,\n undefined,\n );\n }\n\n /**\n * Creates a new signing public key from an Sr25519 public key.\n *\n * @param key - An Sr25519 public key\n * @returns A new signing public key containing the Sr25519 key\n */\n static fromSr25519(key: Sr25519PublicKey): SigningPublicKey {\n return new SigningPublicKey(\n SignatureScheme.Sr25519,\n undefined,\n undefined,\n undefined,\n key,\n undefined,\n );\n }\n\n /**\n * Creates a new signing public key from an MLDSAPublicKey.\n *\n * @param key - An MLDSAPublicKey\n * @returns A new signing public key containing the MLDSA key\n */\n static fromMldsa(key: MLDSAPublicKey): SigningPublicKey {\n // Determine the SignatureScheme based on the MLDSA level\n let scheme: SignatureScheme;\n switch (key.level()) {\n case MLDSALevel.MLDSA44:\n scheme = SignatureScheme.MLDSA44;\n break;\n case MLDSALevel.MLDSA65:\n scheme = SignatureScheme.MLDSA65;\n break;\n case MLDSALevel.MLDSA87:\n scheme = SignatureScheme.MLDSA87;\n break;\n default:\n throw new Error(`Unknown MLDSA level: ${key.level()}`);\n }\n return new SigningPublicKey(scheme, undefined, undefined, undefined, undefined, key);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the signature scheme of this key.\n */\n scheme(): SignatureScheme {\n return this._type;\n }\n\n /**\n * Returns a human-readable string identifying the key type.\n * @returns A string like \"Ed25519\", \"Schnorr\", \"ECDSA\", \"Sr25519\", \"MLDSA-44\", etc.\n */\n keyType(): string {\n switch (this._type) {\n case SignatureScheme.Ed25519:\n return \"Ed25519\";\n case SignatureScheme.Schnorr:\n return \"Schnorr\";\n case SignatureScheme.Ecdsa:\n return \"ECDSA\";\n case SignatureScheme.Sr25519:\n return \"Sr25519\";\n case SignatureScheme.MLDSA44:\n return \"MLDSA-44\";\n case SignatureScheme.MLDSA65:\n return \"MLDSA-65\";\n case SignatureScheme.MLDSA87:\n return \"MLDSA-87\";\n case SignatureScheme.SshEd25519:\n return \"SSH-Ed25519\";\n case SignatureScheme.SshDsa:\n return \"SSH-DSA\";\n case SignatureScheme.SshEcdsaP256:\n return \"SSH-ECDSA-P256\";\n case SignatureScheme.SshEcdsaP384:\n return \"SSH-ECDSA-P384\";\n default:\n return this._type;\n }\n }\n\n /**\n * Returns the underlying Schnorr public key if this is a Schnorr key.\n *\n * @returns The SchnorrPublicKey if this is a Schnorr key, null otherwise\n */\n toSchnorr(): SchnorrPublicKey | null {\n if (this._type === SignatureScheme.Schnorr && this._schnorrKey !== undefined) {\n return this._schnorrKey;\n }\n return null;\n }\n\n /**\n * Returns the underlying ECDSA public key if this is an ECDSA key.\n *\n * @returns The ECPublicKey if this is an ECDSA key, null otherwise\n */\n toEcdsa(): ECPublicKey | null {\n if (this._type === SignatureScheme.Ecdsa && this._ecdsaKey !== undefined) {\n return this._ecdsaKey;\n }\n return null;\n }\n\n /**\n * Returns the underlying Ed25519 public key if this is an Ed25519 key.\n *\n * @returns The Ed25519 public key if this is an Ed25519 key, null otherwise\n */\n toEd25519(): Ed25519PublicKey | null {\n if (this._type === SignatureScheme.Ed25519 && this._ed25519Key !== undefined) {\n return this._ed25519Key;\n }\n return null;\n }\n\n /**\n * Returns the underlying Sr25519 public key if this is an Sr25519 key.\n *\n * @returns The Sr25519 public key if this is an Sr25519 key, null otherwise\n */\n toSr25519(): Sr25519PublicKey | null {\n if (this._type === SignatureScheme.Sr25519 && this._sr25519Key !== undefined) {\n return this._sr25519Key;\n }\n return null;\n }\n\n /**\n * Checks if this is a Schnorr signing key.\n */\n isSchnorr(): boolean {\n return this._type === SignatureScheme.Schnorr;\n }\n\n /**\n * Checks if this is an ECDSA signing key.\n */\n isEcdsa(): boolean {\n return this._type === SignatureScheme.Ecdsa;\n }\n\n /**\n * Checks if this is an Ed25519 signing key.\n */\n isEd25519(): boolean {\n return this._type === SignatureScheme.Ed25519;\n }\n\n /**\n * Checks if this is an Sr25519 signing key.\n */\n isSr25519(): boolean {\n return this._type === SignatureScheme.Sr25519;\n }\n\n /**\n * Returns the underlying MLDSA public key if this is an MLDSA key.\n *\n * @returns The MLDSAPublicKey if this is an MLDSA key, null otherwise\n */\n toMldsa(): MLDSAPublicKey | null {\n if (isMldsaScheme(this._type) && this._mldsaKey !== undefined) {\n return this._mldsaKey;\n }\n return null;\n }\n\n /**\n * Checks if this is an MLDSA signing key.\n */\n isMldsa(): boolean {\n return isMldsaScheme(this._type);\n }\n\n /**\n * Compare with another SigningPublicKey.\n */\n equals(other: SigningPublicKey): boolean {\n if (this._type !== other._type) return false;\n switch (this._type) {\n case SignatureScheme.Schnorr:\n if (this._schnorrKey === undefined || other._schnorrKey === undefined) return false;\n return this._schnorrKey.equals(other._schnorrKey);\n case SignatureScheme.Ecdsa:\n if (this._ecdsaKey === undefined || other._ecdsaKey === undefined) return false;\n return this._ecdsaKey.equals(other._ecdsaKey);\n case SignatureScheme.Ed25519:\n if (this._ed25519Key === undefined || other._ed25519Key === undefined) return false;\n return this._ed25519Key.equals(other._ed25519Key);\n case SignatureScheme.Sr25519:\n if (this._sr25519Key === undefined || other._sr25519Key === undefined) return false;\n return this._sr25519Key.equals(other._sr25519Key);\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87:\n if (this._mldsaKey === undefined || other._mldsaKey === undefined) return false;\n return this._mldsaKey.equals(other._mldsaKey);\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n return false;\n }\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n switch (this._type) {\n case SignatureScheme.Schnorr:\n return `SigningPublicKey(${this._type}, ${this._schnorrKey?.toHex().substring(0, 16)}...)`;\n case SignatureScheme.Ecdsa:\n return `SigningPublicKey(${this._type}, ${this._ecdsaKey?.toHex().substring(0, 16)}...)`;\n case SignatureScheme.Ed25519:\n return `SigningPublicKey(${this._type}, ${this._ed25519Key?.toHex().substring(0, 16)}...)`;\n case SignatureScheme.Sr25519:\n return `SigningPublicKey(${this._type}, ${this._sr25519Key?.toHex().substring(0, 16)}...)`;\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87:\n return `SigningPublicKey(${this._type}, ${this._mldsaKey?.toString().substring(0, 30)}...)`;\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n return `SigningPublicKey(${this._type}, SSH scheme not supported)`;\n }\n }\n\n // ============================================================================\n // ReferenceProvider Interface\n // ============================================================================\n\n /**\n * Returns a unique reference to this SigningPublicKey instance.\n *\n * The reference is derived from the SHA-256 hash of the tagged CBOR\n * representation, providing a unique, content-addressable identifier.\n */\n reference(): Reference {\n const digest = Digest.fromImage(this.taggedCborData());\n return Reference.from(digest);\n }\n\n // ============================================================================\n // Verifier Interface\n // ============================================================================\n\n /**\n * Verifies a signature against a message.\n *\n * @param signature - The signature to verify\n * @param message - The message that was allegedly signed\n * @returns `true` if the signature is valid, `false` otherwise\n */\n verify(signature: Signature, message: Uint8Array): boolean {\n // Check that signature scheme matches\n if (signature.scheme() !== this._type) {\n return false;\n }\n\n switch (this._type) {\n case SignatureScheme.Schnorr: {\n if (this._schnorrKey === undefined) {\n return false;\n }\n const sigData = signature.toSchnorr();\n if (sigData === null) {\n return false;\n }\n try {\n return this._schnorrKey.schnorrVerify(sigData, message);\n } catch {\n return false;\n }\n }\n case SignatureScheme.Ecdsa: {\n if (this._ecdsaKey === undefined) {\n return false;\n }\n const sigData = signature.toEcdsa();\n if (sigData === null) {\n return false;\n }\n try {\n return this._ecdsaKey.verify(sigData, message);\n } catch {\n return false;\n }\n }\n case SignatureScheme.Ed25519: {\n if (this._ed25519Key === undefined) {\n return false;\n }\n const sigData = signature.toEd25519();\n if (sigData === null) {\n return false;\n }\n try {\n return this._ed25519Key.verify(message, sigData);\n } catch {\n return false;\n }\n }\n case SignatureScheme.Sr25519: {\n if (this._sr25519Key === undefined) {\n return false;\n }\n const sigData = signature.toSr25519();\n if (sigData === null) {\n return false;\n }\n try {\n return this._sr25519Key.verify(sigData, message);\n } catch {\n return false;\n }\n }\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87: {\n if (this._mldsaKey === undefined) {\n return false;\n }\n const mldsaSig = signature.toMldsa();\n if (mldsaSig === null) {\n return false;\n }\n try {\n return this._mldsaKey.verify(mldsaSig, message);\n } catch {\n return false;\n }\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n return false;\n }\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with SigningPublicKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SIGNING_PUBLIC_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format (matching Rust bc-components):\n * - Schnorr: h'<32-byte-x-only-public-key>' (bare byte string)\n * - ECDSA: [1, h'<33-byte-compressed-public-key>']\n * - Ed25519: [2, h'<32-byte-public-key>']\n * - Sr25519: [3, h'<32-byte-public-key>']\n */\n untaggedCbor(): Cbor {\n switch (this._type) {\n case SignatureScheme.Schnorr: {\n if (this._schnorrKey === undefined) {\n throw new Error(\"Schnorr public key is missing\");\n }\n // Rust: CBOR::to_byte_string(key.data()) - bare byte string\n return toByteString(this._schnorrKey.toData());\n }\n case SignatureScheme.Ecdsa: {\n if (this._ecdsaKey === undefined) {\n throw new Error(\"ECDSA public key is missing\");\n }\n return cbor([1, toByteString(this._ecdsaKey.toData())]);\n }\n case SignatureScheme.Ed25519: {\n if (this._ed25519Key === undefined) {\n throw new Error(\"Ed25519 public key is missing\");\n }\n return cbor([2, toByteString(this._ed25519Key.toData())]);\n }\n case SignatureScheme.Sr25519: {\n if (this._sr25519Key === undefined) {\n throw new Error(\"Sr25519 public key is missing\");\n }\n return cbor([3, toByteString(this._sr25519Key.toData())]);\n }\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87: {\n if (this._mldsaKey === undefined) {\n throw new Error(\"MLDSA public key is missing\");\n }\n // Rust: delegates to MLDSAPublicKey (which produces tagged CBOR)\n return this._mldsaKey.taggedCbor();\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n throw new Error(`SSH signature scheme ${this._type} is not supported for CBOR encoding`);\n }\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a SigningPublicKey by decoding it from untagged CBOR.\n *\n * Format (matching Rust bc-components):\n * - h'<32-byte-key>' (bare byte string) for Schnorr\n * - [1, h'<33-byte-key>'] for ECDSA\n * - [2, h'<32-byte-key>'] for Ed25519\n * - [3, h'<32-byte-key>'] for Sr25519\n */\n fromUntaggedCbor(cborValue: Cbor): SigningPublicKey {\n // Rust format: Schnorr is a bare byte string\n if (isBytes(cborValue)) {\n const keyData = expectBytes(cborValue);\n return SigningPublicKey.fromSchnorr(SchnorrPublicKey.from(keyData));\n }\n\n // Array format for ECDSA, Ed25519, Sr25519\n if (isArray(cborValue)) {\n const elements = expectArray(cborValue);\n\n if (elements.length !== 2) {\n throw new Error(\"SigningPublicKey array must have 2 elements\");\n }\n\n const discriminator = expectUnsigned(elements[0]);\n const keyData = expectBytes(elements[1]);\n\n switch (Number(discriminator)) {\n case 1: // ECDSA\n return SigningPublicKey.fromEcdsa(ECPublicKey.from(keyData));\n case 2: // Ed25519\n return SigningPublicKey.fromEd25519(Ed25519PublicKey.from(keyData));\n case 3: // Sr25519\n return SigningPublicKey.fromSr25519(Sr25519PublicKey.from(keyData));\n default:\n throw new Error(`Unknown SigningPublicKey discriminator: ${discriminator}`);\n }\n }\n\n // Tagged format for MLDSA\n if (isTagged(cborValue)) {\n const tagged = cborValue.asTagged();\n if (tagged?.[0].value === TAG_MLDSA_PUBLIC_KEY.value) {\n const mldsaKey = MLDSAPublicKey.fromTaggedCbor(cborValue);\n return SigningPublicKey.fromMldsa(mldsaKey);\n }\n }\n\n throw new Error(\n \"SigningPublicKey must be a byte string (Schnorr), array (ECDSA/Ed25519/Sr25519), or tagged MLDSA\",\n );\n }\n\n /**\n * Creates a SigningPublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): SigningPublicKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): SigningPublicKey {\n // Create a dummy instance for accessing instance methods\n const dummy = new SigningPublicKey(\n SignatureScheme.Ed25519,\n undefined, // schnorrKey\n undefined, // ecdsaKey\n Ed25519PublicKey.from(new Uint8Array(ED25519_PUBLIC_KEY_SIZE)), // ed25519Key\n );\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): SigningPublicKey {\n const cborValue = decodeCbor(data);\n return SigningPublicKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): SigningPublicKey {\n const cborValue = decodeCbor(data);\n const dummy = new SigningPublicKey(\n SignatureScheme.Ed25519,\n undefined, // schnorrKey\n undefined, // ecdsaKey\n Ed25519PublicKey.from(new Uint8Array(ED25519_PUBLIC_KEY_SIZE)), // ed25519Key\n );\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR (Uniform Resource) Serialization\n // ============================================================================\n\n /**\n * Get the UR type for signing public keys.\n */\n static readonly UR_TYPE = \"signing-public-key\";\n\n /**\n * Returns the UR representation of the signing public key.\n */\n ur(): UR {\n return UR.new(SigningPublicKey.UR_TYPE, this.taggedCbor());\n }\n\n /**\n * Returns the UR string representation of the signing public key.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a SigningPublicKey from a UR.\n */\n static fromUR(ur: UR): SigningPublicKey {\n ur.checkType(SigningPublicKey.UR_TYPE);\n return SigningPublicKey.fromTaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a SigningPublicKey from a UR string.\n */\n static fromURString(urString: string): SigningPublicKey {\n const ur = UR.fromURString(urString);\n return SigningPublicKey.fromUR(ur);\n }\n\n /**\n * Alias for fromURString for Rust API compatibility.\n */\n static fromUrString(urString: string): SigningPublicKey {\n return SigningPublicKey.fromURString(urString);\n }\n\n // ============================================================================\n // SSH Format\n // ============================================================================\n\n /**\n * Converts the public key to SSH format.\n * Currently only supports Ed25519 keys.\n */\n toSsh(comment?: string): string {\n if (this._type !== SignatureScheme.Ed25519) {\n throw new Error(`SSH export only supports Ed25519 keys, got ${this._type}`);\n }\n if (this._ed25519Key === undefined) {\n throw new Error(\"Ed25519 key not initialized\");\n }\n\n // SSH format: ssh-ed25519 <base64-encoded-data> [comment]\n // The data is: 4-byte length of \"ssh-ed25519\" + \"ssh-ed25519\" + 4-byte length of key + key bytes\n const algorithm = \"ssh-ed25519\";\n const algorithmBytes = new TextEncoder().encode(algorithm);\n const keyBytes = this._ed25519Key.toData();\n const keyLen = keyBytes.length;\n\n // Build the blob: [4-byte length][algorithm][4-byte length][key]\n const totalLength = 4 + algorithmBytes.length + 4 + keyLen;\n const blob = new Uint8Array(totalLength);\n let offset = 0;\n\n // Write algorithm length (big-endian)\n blob[offset++] = (algorithmBytes.length >> 24) & 0xff;\n blob[offset++] = (algorithmBytes.length >> 16) & 0xff;\n blob[offset++] = (algorithmBytes.length >> 8) & 0xff;\n blob[offset++] = algorithmBytes.length & 0xff;\n\n // Write algorithm\n blob.set(algorithmBytes, offset);\n offset += algorithmBytes.length;\n\n // Write key length (big-endian)\n blob[offset++] = (keyLen >> 24) & 0xff;\n blob[offset++] = (keyLen >> 16) & 0xff;\n blob[offset++] = (keyLen >> 8) & 0xff;\n blob[offset++] = keyLen & 0xff;\n\n // Write key\n blob.set(keyBytes, offset);\n\n // Base64 encode the blob\n let base64 = \"\";\n const bytes = blob;\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n for (let i = 0; i < bytes.length; i += 3) {\n const b0 = bytes[i];\n const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;\n const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;\n base64 += chars[(b0 >> 2) & 0x3f];\n base64 += chars[((b0 << 4) | (b1 >> 4)) & 0x3f];\n base64 += i + 1 < bytes.length ? chars[((b1 << 2) | (b2 >> 6)) & 0x3f] : \"=\";\n base64 += i + 2 < bytes.length ? chars[b2 & 0x3f] : \"=\";\n }\n\n const result = `${algorithm} ${base64}`;\n return comment !== undefined && comment !== \"\" ? `${result} ${comment}` : result;\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * A private key used for creating digital signatures.\n *\n * `SigningPrivateKey` is a type representing different types of signing\n * private keys. Supports Schnorr, ECDSA, Ed25519, and SR25519.\n *\n * This type implements the `Signer` interface, allowing it to create signatures.\n *\n * # CBOR Serialization\n *\n * `SigningPrivateKey` is serialized to CBOR with tag 40021.\n *\n * The CBOR encoding (matching Rust bc-components):\n * - Schnorr: `#6.40021(h'<32-byte-private-key>')` (bare byte string)\n * - ECDSA: `#6.40021([1, h'<32-byte-private-key>'])`\n * - Ed25519: `#6.40021([2, h'<32-byte-private-key>'])`\n * - SR25519: `#6.40021([3, h'<32-byte-seed>'])`\n *\n * Ported from bc-components-rust/src/signing/signing_private_key.rs\n */\n\nimport { ED25519_PRIVATE_KEY_SIZE } from \"@bcts/crypto\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n toByteString,\n expectArray,\n expectBytes,\n expectUnsigned,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n isBytes,\n isArray,\n isTagged,\n} from \"@bcts/dcbor\";\nimport {\n SIGNING_PRIVATE_KEY as TAG_SIGNING_PRIVATE_KEY,\n MLDSA_PRIVATE_KEY as TAG_MLDSA_PRIVATE_KEY,\n} from \"@bcts/tags\";\nimport { Ed25519PrivateKey } from \"../ed25519/ed25519-private-key.js\";\nimport { Sr25519PrivateKey } from \"../sr25519/sr25519-private-key.js\";\nimport { ECPrivateKey } from \"../ec-key/ec-private-key.js\";\nimport { MLDSAPrivateKey } from \"../mldsa/mldsa-private-key.js\";\nimport { MLDSALevel } from \"../mldsa/mldsa-level.js\";\nimport { SignatureScheme, isMldsaScheme, type SigningOptions } from \"./signature-scheme.js\";\nimport { Signature } from \"./signature.js\";\nimport { SigningPublicKey } from \"./signing-public-key.js\";\nimport type { Signer, Verifier } from \"./signer.js\";\nimport { Reference, type ReferenceProvider } from \"../reference.js\";\nimport { Digest } from \"../digest.js\";\nimport { UR } from \"@bcts/uniform-resources\";\n\n/**\n * A private key used for creating digital signatures.\n *\n * Currently supports:\n * - Schnorr private keys (32 bytes, secp256k1) - bare byte string in CBOR\n * - ECDSA private keys (32 bytes, secp256k1) - discriminator 1\n * - Ed25519 private keys (32 bytes) - discriminator 2\n * - SR25519 private keys (32-byte seed) - discriminator 3\n * - MLDSA private keys (post-quantum) - tagged CBOR delegating to MLDSAPrivateKey\n */\nexport class SigningPrivateKey\n implements\n Signer,\n Verifier,\n ReferenceProvider,\n CborTaggedEncodable,\n CborTaggedDecodable<SigningPrivateKey>\n{\n private readonly _type: SignatureScheme;\n private readonly _ecKey: ECPrivateKey | undefined;\n private readonly _ed25519Key: Ed25519PrivateKey | undefined;\n private readonly _sr25519Key: Sr25519PrivateKey | undefined;\n private readonly _mldsaKey: MLDSAPrivateKey | undefined;\n\n private constructor(\n type: SignatureScheme,\n ecKey?: ECPrivateKey,\n ed25519Key?: Ed25519PrivateKey,\n sr25519Key?: Sr25519PrivateKey,\n mldsaKey?: MLDSAPrivateKey,\n ) {\n this._type = type;\n this._ecKey = ecKey;\n this._ed25519Key = ed25519Key;\n this._sr25519Key = sr25519Key;\n this._mldsaKey = mldsaKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Creates a new Schnorr signing private key from an ECPrivateKey.\n *\n * @param key - The EC private key to use for Schnorr signing\n * @returns A new Schnorr signing private key\n */\n static newSchnorr(key: ECPrivateKey): SigningPrivateKey {\n return new SigningPrivateKey(SignatureScheme.Schnorr, key, undefined, undefined, undefined);\n }\n\n /**\n * Creates a new ECDSA signing private key from an ECPrivateKey.\n *\n * @param key - The EC private key to use for ECDSA signing\n * @returns A new ECDSA signing private key\n */\n static newEcdsa(key: ECPrivateKey): SigningPrivateKey {\n return new SigningPrivateKey(SignatureScheme.Ecdsa, key, undefined, undefined, undefined);\n }\n\n /**\n * Creates a new Ed25519 signing private key from an Ed25519PrivateKey.\n *\n * @param key - The Ed25519 private key to use\n * @returns A new Ed25519 signing private key\n */\n static newEd25519(key: Ed25519PrivateKey): SigningPrivateKey {\n return new SigningPrivateKey(SignatureScheme.Ed25519, undefined, key, undefined, undefined);\n }\n\n /**\n * Creates a new SR25519 signing private key from an Sr25519PrivateKey.\n *\n * @param key - The SR25519 private key to use\n * @returns A new SR25519 signing private key\n */\n static newSr25519(key: Sr25519PrivateKey): SigningPrivateKey {\n return new SigningPrivateKey(SignatureScheme.Sr25519, undefined, undefined, key, undefined);\n }\n\n /**\n * Creates a new MLDSA signing private key from an MLDSAPrivateKey.\n *\n * @param key - The MLDSA private key to use\n * @returns A new MLDSA signing private key\n */\n static newMldsa(key: MLDSAPrivateKey): SigningPrivateKey {\n // Determine the SignatureScheme based on the MLDSA level\n let scheme: SignatureScheme;\n switch (key.level()) {\n case MLDSALevel.MLDSA44:\n scheme = SignatureScheme.MLDSA44;\n break;\n case MLDSALevel.MLDSA65:\n scheme = SignatureScheme.MLDSA65;\n break;\n case MLDSALevel.MLDSA87:\n scheme = SignatureScheme.MLDSA87;\n break;\n default:\n throw new Error(`Unknown MLDSA level: ${key.level()}`);\n }\n return new SigningPrivateKey(scheme, undefined, undefined, undefined, key);\n }\n\n /**\n * Creates a new random Ed25519 signing private key.\n *\n * @returns A new random Ed25519 signing private key\n */\n static random(): SigningPrivateKey {\n return SigningPrivateKey.newEd25519(Ed25519PrivateKey.random());\n }\n\n /**\n * Creates a new random Schnorr signing private key.\n *\n * @returns A new random Schnorr signing private key\n */\n static randomSchnorr(): SigningPrivateKey {\n return SigningPrivateKey.newSchnorr(ECPrivateKey.random());\n }\n\n /**\n * Creates a new random ECDSA signing private key.\n *\n * @returns A new random ECDSA signing private key\n */\n static randomEcdsa(): SigningPrivateKey {\n return SigningPrivateKey.newEcdsa(ECPrivateKey.random());\n }\n\n /**\n * Creates a new random SR25519 signing private key.\n *\n * @returns A new random SR25519 signing private key\n */\n static randomSr25519(): SigningPrivateKey {\n return SigningPrivateKey.newSr25519(Sr25519PrivateKey.random());\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the signature scheme of this key.\n */\n scheme(): SignatureScheme {\n return this._type;\n }\n\n /**\n * Returns a human-readable string identifying the key type.\n * @returns A string like \"Ed25519\", \"Schnorr\", \"ECDSA\", \"Sr25519\", \"MLDSA-44\", etc.\n */\n keyType(): string {\n switch (this._type) {\n case SignatureScheme.Ed25519:\n return \"Ed25519\";\n case SignatureScheme.Schnorr:\n return \"Schnorr\";\n case SignatureScheme.Ecdsa:\n return \"ECDSA\";\n case SignatureScheme.Sr25519:\n return \"Sr25519\";\n case SignatureScheme.MLDSA44:\n return \"MLDSA-44\";\n case SignatureScheme.MLDSA65:\n return \"MLDSA-65\";\n case SignatureScheme.MLDSA87:\n return \"MLDSA-87\";\n case SignatureScheme.SshEd25519:\n return \"SSH-Ed25519\";\n case SignatureScheme.SshDsa:\n return \"SSH-DSA\";\n case SignatureScheme.SshEcdsaP256:\n return \"SSH-ECDSA-P256\";\n case SignatureScheme.SshEcdsaP384:\n return \"SSH-ECDSA-P384\";\n default:\n return this._type;\n }\n }\n\n /**\n * Returns the underlying EC private key if this is a Schnorr or ECDSA key.\n *\n * @returns The EC private key if this is a Schnorr or ECDSA key, null otherwise\n */\n toEc(): ECPrivateKey | null {\n if (\n (this._type === SignatureScheme.Schnorr || this._type === SignatureScheme.Ecdsa) &&\n this._ecKey !== undefined\n ) {\n return this._ecKey;\n }\n return null;\n }\n\n /**\n * Returns the underlying Schnorr private key if this is a Schnorr key.\n *\n * @returns The EC private key if this is a Schnorr key, null otherwise\n */\n toSchnorr(): ECPrivateKey | null {\n if (this._type === SignatureScheme.Schnorr && this._ecKey !== undefined) {\n return this._ecKey;\n }\n return null;\n }\n\n /**\n * Returns the underlying ECDSA private key if this is an ECDSA key.\n *\n * @returns The EC private key if this is an ECDSA key, null otherwise\n */\n toEcdsa(): ECPrivateKey | null {\n if (this._type === SignatureScheme.Ecdsa && this._ecKey !== undefined) {\n return this._ecKey;\n }\n return null;\n }\n\n /**\n * Returns the underlying Ed25519 private key if this is an Ed25519 key.\n *\n * @returns The Ed25519 private key if this is an Ed25519 key, null otherwise\n */\n toEd25519(): Ed25519PrivateKey | null {\n if (this._type === SignatureScheme.Ed25519 && this._ed25519Key !== undefined) {\n return this._ed25519Key;\n }\n return null;\n }\n\n /**\n * Returns the underlying Sr25519 private key if this is an Sr25519 key.\n *\n * @returns The Sr25519 private key if this is an Sr25519 key, null otherwise\n */\n toSr25519(): Sr25519PrivateKey | null {\n if (this._type === SignatureScheme.Sr25519 && this._sr25519Key !== undefined) {\n return this._sr25519Key;\n }\n return null;\n }\n\n /**\n * Returns the underlying MLDSA private key if this is an MLDSA key.\n *\n * @returns The MLDSA private key if this is an MLDSA key, null otherwise\n */\n toMldsa(): MLDSAPrivateKey | null {\n if (isMldsaScheme(this._type) && this._mldsaKey !== undefined) {\n return this._mldsaKey;\n }\n return null;\n }\n\n /**\n * Checks if this is a Schnorr signing key.\n */\n isSchnorr(): boolean {\n return this._type === SignatureScheme.Schnorr;\n }\n\n /**\n * Checks if this is an ECDSA signing key.\n */\n isEcdsa(): boolean {\n return this._type === SignatureScheme.Ecdsa;\n }\n\n /**\n * Checks if this is an Ed25519 signing key.\n */\n isEd25519(): boolean {\n return this._type === SignatureScheme.Ed25519;\n }\n\n /**\n * Checks if this is an Sr25519 signing key.\n */\n isSr25519(): boolean {\n return this._type === SignatureScheme.Sr25519;\n }\n\n /**\n * Checks if this is an MLDSA signing key.\n */\n isMldsa(): boolean {\n return isMldsaScheme(this._type);\n }\n\n /**\n * Derives the corresponding public key for this private key.\n *\n * @returns The public key corresponding to this private key\n */\n publicKey(): SigningPublicKey {\n switch (this._type) {\n case SignatureScheme.Schnorr: {\n if (this._ecKey === undefined) {\n throw new Error(\"EC private key is missing\");\n }\n return SigningPublicKey.fromSchnorr(this._ecKey.schnorrPublicKey());\n }\n case SignatureScheme.Ecdsa: {\n if (this._ecKey === undefined) {\n throw new Error(\"EC private key is missing\");\n }\n return SigningPublicKey.fromEcdsa(this._ecKey.publicKey());\n }\n case SignatureScheme.Ed25519: {\n if (this._ed25519Key === undefined) {\n throw new Error(\"Ed25519 private key is missing\");\n }\n return SigningPublicKey.fromEd25519(this._ed25519Key.publicKey());\n }\n case SignatureScheme.Sr25519: {\n if (this._sr25519Key === undefined) {\n throw new Error(\"Sr25519 private key is missing\");\n }\n return SigningPublicKey.fromSr25519(this._sr25519Key.publicKey());\n }\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87: {\n if (this._mldsaKey === undefined) {\n throw new Error(\"MLDSA private key is missing\");\n }\n return SigningPublicKey.fromMldsa(this._mldsaKey.publicKey());\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n throw new Error(`SSH signature scheme ${this._type} is not supported`);\n }\n }\n\n /**\n * Compare with another SigningPrivateKey.\n */\n equals(other: SigningPrivateKey): boolean {\n if (this._type !== other._type) return false;\n switch (this._type) {\n case SignatureScheme.Schnorr:\n case SignatureScheme.Ecdsa:\n if (this._ecKey === undefined || other._ecKey === undefined) return false;\n return this._ecKey.equals(other._ecKey);\n case SignatureScheme.Ed25519:\n if (this._ed25519Key === undefined || other._ed25519Key === undefined) return false;\n return this._ed25519Key.equals(other._ed25519Key);\n case SignatureScheme.Sr25519:\n if (this._sr25519Key === undefined || other._sr25519Key === undefined) return false;\n return this._sr25519Key.equals(other._sr25519Key);\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87:\n if (this._mldsaKey === undefined || other._mldsaKey === undefined) return false;\n return this._mldsaKey.equals(other._mldsaKey);\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n return false;\n }\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `SigningPrivateKey(${this._type})`;\n }\n\n // ============================================================================\n // ReferenceProvider Interface\n // ============================================================================\n\n /**\n * Returns a unique reference to this SigningPrivateKey instance.\n *\n * The reference is derived from the SHA-256 hash of the tagged CBOR\n * representation, providing a unique, content-addressable identifier.\n */\n reference(): Reference {\n const digest = Digest.fromImage(this.taggedCborData());\n return Reference.from(digest);\n }\n\n // ============================================================================\n // Signer Interface\n // ============================================================================\n\n /**\n * Signs a message with optional signing options.\n *\n * Different signature schemes may use the options differently:\n * - Schnorr: Can accept a custom random number generator via SigningOptions.Schnorr\n * - SSH: Would require namespace and hash algorithm (not yet implemented)\n * - Other schemes (ECDSA, Ed25519, Sr25519, MLDSA): Options are ignored\n *\n * @param message - The message to sign\n * @param options - Optional signing options\n * @returns The digital signature\n */\n signWithOptions(message: Uint8Array, options?: SigningOptions): Signature {\n switch (this._type) {\n case SignatureScheme.Schnorr: {\n if (this._ecKey === undefined) {\n throw new Error(\"EC private key is missing\");\n }\n // If Schnorr options with custom RNG are provided, use them\n if (options?.type === \"Schnorr\") {\n const sigData = this._ecKey.schnorrSignUsing(message, options.rng);\n return Signature.schnorrFromData(sigData);\n }\n // Otherwise use default RNG\n const sigData = this._ecKey.schnorrSign(message);\n return Signature.schnorrFromData(sigData);\n }\n case SignatureScheme.Ecdsa: {\n if (this._ecKey === undefined) {\n throw new Error(\"EC private key is missing\");\n }\n const sigData = this._ecKey.ecdsaSign(message);\n return Signature.ecdsaFromData(sigData);\n }\n case SignatureScheme.Ed25519: {\n if (this._ed25519Key === undefined) {\n throw new Error(\"Ed25519 private key is missing\");\n }\n const sigData = this._ed25519Key.sign(message);\n return Signature.ed25519FromData(sigData);\n }\n case SignatureScheme.Sr25519: {\n if (this._sr25519Key === undefined) {\n throw new Error(\"Sr25519 private key is missing\");\n }\n const sigData = this._sr25519Key.sign(message);\n return Signature.sr25519FromData(sigData);\n }\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87: {\n if (this._mldsaKey === undefined) {\n throw new Error(\"MLDSA private key is missing\");\n }\n const mldsaSig = this._mldsaKey.sign(message);\n return Signature.mldsaFromSignature(mldsaSig);\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n // SSH signing requires SigningOptions.Ssh with namespace and hash algorithm\n if (options?.type === \"Ssh\") {\n throw new Error(\n `SSH signature scheme ${this._type} is not yet implemented. ` +\n `Namespace: ${options.namespace}, hashAlg: ${options.hashAlg}`,\n );\n }\n throw new Error(`SSH signature scheme ${this._type} requires SigningOptions.Ssh`);\n }\n }\n\n /**\n * Signs a message using default options.\n *\n * This is a convenience method that calls `signWithOptions` with no options.\n *\n * @param message - The message to sign\n * @returns The digital signature\n */\n sign(message: Uint8Array): Signature {\n return this.signWithOptions(message);\n }\n\n // ============================================================================\n // Verifier Interface\n // ============================================================================\n\n /**\n * Verifies a signature against a message.\n *\n * @param signature - The signature to verify\n * @param message - The message that was allegedly signed\n * @returns `true` if the signature is valid, `false` otherwise\n */\n verify(signature: Signature, message: Uint8Array): boolean {\n return this.publicKey().verify(signature, message);\n }\n\n // ============================================================================\n // Scheme-Specific Sign Methods\n // ============================================================================\n\n /**\n * Signs a message using Schnorr with the provided random number generator.\n *\n * This method is only valid for Schnorr keys.\n *\n * @param message - The message to sign\n * @param rng - The random number generator to use for signature creation\n * @returns The Schnorr signature\n * @throws Error if this is not a Schnorr key\n */\n schnorrSign(message: Uint8Array, rng: RandomNumberGenerator): Signature {\n const privateKey = this.toSchnorr();\n if (privateKey === null) {\n throw new Error(\"Invalid key type for Schnorr signing\");\n }\n const sigData = privateKey.schnorrSignUsing(message, rng);\n return Signature.schnorrFromData(sigData);\n }\n\n /**\n * Signs a message using ECDSA.\n *\n * This method is only valid for ECDSA keys.\n *\n * @param message - The message to sign\n * @returns The ECDSA signature\n * @throws Error if this is not an ECDSA key\n */\n ecdsaSign(message: Uint8Array): Signature {\n const privateKey = this.toEcdsa();\n if (privateKey === null) {\n throw new Error(\"Invalid key type for ECDSA signing\");\n }\n const sigData = privateKey.ecdsaSign(message);\n return Signature.ecdsaFromData(sigData);\n }\n\n /**\n * Signs a message using Ed25519.\n *\n * This method is only valid for Ed25519 keys.\n *\n * @param message - The message to sign\n * @returns The Ed25519 signature\n * @throws Error if this is not an Ed25519 key\n */\n ed25519Sign(message: Uint8Array): Signature {\n const privateKey = this.toEd25519();\n if (privateKey === null) {\n throw new Error(\"Invalid key type for Ed25519 signing\");\n }\n const sigData = privateKey.sign(message);\n return Signature.ed25519FromData(sigData);\n }\n\n /**\n * Signs a message using SR25519.\n *\n * This method is only valid for SR25519 keys.\n *\n * @param message - The message to sign\n * @returns The SR25519 signature\n * @throws Error if this is not an SR25519 key\n */\n sr25519Sign(message: Uint8Array): Signature {\n const privateKey = this.toSr25519();\n if (privateKey === null) {\n throw new Error(\"Invalid key type for SR25519 signing\");\n }\n const sigData = privateKey.sign(message);\n return Signature.sr25519FromData(sigData);\n }\n\n /**\n * Signs a message using ML-DSA.\n *\n * This method is only valid for MLDSA keys.\n *\n * @param message - The message to sign\n * @returns The ML-DSA signature\n * @throws Error if this is not an MLDSA key\n */\n mldsaSign(message: Uint8Array): Signature {\n const privateKey = this.toMldsa();\n if (privateKey === null) {\n throw new Error(\"Invalid key type for MLDSA signing\");\n }\n const mldsaSig = privateKey.sign(message);\n return Signature.mldsaFromSignature(mldsaSig);\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with SigningPrivateKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SIGNING_PRIVATE_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format (matching Rust bc-components):\n * - Schnorr: h'<32-byte-private-key>' (bare byte string)\n * - ECDSA: [1, h'<32-byte-private-key>']\n * - Ed25519: [2, h'<32-byte-private-key>']\n * - Sr25519: [3, h'<32-byte-seed>']\n * - MLDSA: delegates to MLDSAPrivateKey (tagged)\n */\n untaggedCbor(): Cbor {\n switch (this._type) {\n case SignatureScheme.Schnorr: {\n if (this._ecKey === undefined) {\n throw new Error(\"EC private key is missing\");\n }\n // Rust: CBOR::to_byte_string(key.data()) - bare byte string\n return toByteString(this._ecKey.toData());\n }\n case SignatureScheme.Ecdsa: {\n if (this._ecKey === undefined) {\n throw new Error(\"EC private key is missing\");\n }\n return cbor([1, toByteString(this._ecKey.toData())]);\n }\n case SignatureScheme.Ed25519: {\n if (this._ed25519Key === undefined) {\n throw new Error(\"Ed25519 private key is missing\");\n }\n return cbor([2, toByteString(this._ed25519Key.toData())]);\n }\n case SignatureScheme.Sr25519: {\n if (this._sr25519Key === undefined) {\n throw new Error(\"Sr25519 private key is missing\");\n }\n return cbor([3, toByteString(this._sr25519Key.toData())]);\n }\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87: {\n if (this._mldsaKey === undefined) {\n throw new Error(\"MLDSA private key is missing\");\n }\n // Rust: delegates to MLDSAPrivateKey (which produces tagged CBOR)\n return this._mldsaKey.taggedCbor();\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n throw new Error(`SSH signature scheme ${this._type} is not supported for CBOR encoding`);\n }\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a SigningPrivateKey by decoding it from untagged CBOR.\n *\n * Format (matching Rust bc-components):\n * - h'<32-byte-key>' (bare byte string) for Schnorr\n * - [1, h'<32-byte-key>'] for ECDSA\n * - [2, h'<32-byte-key>'] for Ed25519\n * - [3, h'<32-byte-seed>'] for Sr25519\n * - tagged MLDSA private key for MLDSA variants\n */\n fromUntaggedCbor(cborValue: Cbor): SigningPrivateKey {\n // Rust format: Schnorr is a bare byte string\n if (isBytes(cborValue)) {\n const keyData = expectBytes(cborValue);\n return SigningPrivateKey.newSchnorr(ECPrivateKey.from(keyData));\n }\n\n // Array format for ECDSA, Ed25519, Sr25519\n if (isArray(cborValue)) {\n const elements = expectArray(cborValue);\n\n if (elements.length !== 2) {\n throw new Error(\"SigningPrivateKey array must have 2 elements\");\n }\n\n const discriminator = expectUnsigned(elements[0]);\n const keyData = expectBytes(elements[1]);\n\n switch (Number(discriminator)) {\n case 1: // ECDSA\n return SigningPrivateKey.newEcdsa(ECPrivateKey.from(keyData));\n case 2: // Ed25519\n return SigningPrivateKey.newEd25519(Ed25519PrivateKey.from(keyData));\n case 3: // Sr25519\n return SigningPrivateKey.newSr25519(Sr25519PrivateKey.from(keyData));\n default:\n throw new Error(`Unknown SigningPrivateKey discriminator: ${discriminator}`);\n }\n }\n\n // Tagged format for MLDSA\n if (isTagged(cborValue)) {\n const tagged = cborValue.asTagged();\n if (tagged?.[0].value === TAG_MLDSA_PRIVATE_KEY.value) {\n const mldsaKey = MLDSAPrivateKey.fromTaggedCbor(cborValue);\n return SigningPrivateKey.newMldsa(mldsaKey);\n }\n }\n\n throw new Error(\n \"SigningPrivateKey must be a byte string (Schnorr), array (ECDSA/Ed25519/Sr25519), or tagged MLDSA\",\n );\n }\n\n /**\n * Creates a SigningPrivateKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): SigningPrivateKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): SigningPrivateKey {\n // Create a dummy instance for accessing instance methods\n const dummy = new SigningPrivateKey(\n SignatureScheme.Ed25519,\n undefined, // ecKey\n Ed25519PrivateKey.from(new Uint8Array(ED25519_PRIVATE_KEY_SIZE)), // ed25519Key\n );\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): SigningPrivateKey {\n const cborValue = decodeCbor(data);\n return SigningPrivateKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): SigningPrivateKey {\n const cborValue = decodeCbor(data);\n const dummy = new SigningPrivateKey(\n SignatureScheme.Ed25519,\n undefined, // ecKey\n Ed25519PrivateKey.from(new Uint8Array(ED25519_PRIVATE_KEY_SIZE)), // ed25519Key\n );\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR (Uniform Resource) Serialization\n // ============================================================================\n\n /**\n * Get the UR type for signing private keys.\n */\n static readonly UR_TYPE = \"signing-private-key\";\n\n /**\n * Returns the UR representation of the signing private key.\n */\n ur(): UR {\n return UR.new(SigningPrivateKey.UR_TYPE, this.taggedCbor());\n }\n\n /**\n * Returns the UR string representation of the signing private key.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a SigningPrivateKey from a UR.\n */\n static fromUR(ur: UR): SigningPrivateKey {\n ur.checkType(SigningPrivateKey.UR_TYPE);\n return SigningPrivateKey.fromTaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a SigningPrivateKey from a UR string.\n */\n static fromURString(urString: string): SigningPrivateKey {\n const ur = UR.fromURString(urString);\n return SigningPrivateKey.fromUR(ur);\n }\n\n /**\n * Alias for fromURString for Rust API compatibility.\n */\n static fromUrString(urString: string): SigningPrivateKey {\n return SigningPrivateKey.fromURString(urString);\n }\n\n // ============================================================================\n // SSH Format\n // ============================================================================\n\n /**\n * Converts the private key to OpenSSH format.\n * Currently only supports Ed25519 keys.\n */\n toSsh(comment?: string): string {\n if (this._type !== SignatureScheme.Ed25519) {\n throw new Error(`SSH export only supports Ed25519 keys, got ${this._type}`);\n }\n if (this._ed25519Key === undefined) {\n throw new Error(\"Ed25519 key not initialized\");\n }\n\n // OpenSSH private key format for Ed25519\n\n const publicKey = this._ed25519Key.publicKey();\n const privateKeyBytes = this._ed25519Key.toData();\n const publicKeyBytes = publicKey.toData();\n\n // For OpenSSH Ed25519, the \"private key\" is actually the 64-byte concatenation of:\n // - 32-byte seed (the actual private key)\n // - 32-byte public key\n const combinedKey = new Uint8Array(64);\n combinedKey.set(privateKeyBytes, 0);\n combinedKey.set(publicKeyBytes, 32);\n\n // Build the OpenSSH private key format (simplified version)\n const algorithm = \"ssh-ed25519\";\n const checkInt = Math.floor(Math.random() * 0xffffffff);\n const checkIntBytes = new Uint8Array(4);\n checkIntBytes[0] = (checkInt >> 24) & 0xff;\n checkIntBytes[1] = (checkInt >> 16) & 0xff;\n checkIntBytes[2] = (checkInt >> 8) & 0xff;\n checkIntBytes[3] = checkInt & 0xff;\n\n // This is a simplified implementation - in practice you'd need bcrypt_pbkdf\n // and proper key wrapping. For now, return a placeholder format.\n const actualComment = comment ?? \"\";\n return `-----BEGIN OPENSSH PRIVATE KEY-----\nPlaceholder for ${algorithm} private key export (${actualComment})\nThis requires bcrypt_pbkdf implementation for proper encryption.\n-----END OPENSSH PRIVATE KEY-----`;\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Supported digital signature schemes.\n *\n * This enum represents the various signature schemes supported in this crate,\n * including Ed25519, SR25519, ECDSA, Schnorr, post-quantum ML-DSA, and SSH-based signatures.\n *\n * Ported from bc-components-rust/src/signing/signature_scheme.rs\n */\n\nimport { type SecureRandomNumberGenerator, type RandomNumberGenerator } from \"@bcts/rand\";\nimport { Ed25519PrivateKey } from \"../ed25519/ed25519-private-key.js\";\nimport { Sr25519PrivateKey } from \"../sr25519/sr25519-private-key.js\";\nimport { ECPrivateKey } from \"../ec-key/ec-private-key.js\";\nimport { MLDSAPrivateKey } from \"../mldsa/mldsa-private-key.js\";\nimport { MLDSALevel } from \"../mldsa/mldsa-level.js\";\nimport { SigningPrivateKey } from \"./signing-private-key.js\";\nimport type { SigningPublicKey } from \"./signing-public-key.js\";\nimport { CryptoError } from \"../error.js\";\n\n/**\n * Supported digital signature schemes.\n *\n * This enum represents the various signature schemes supported in this package.\n * - Schnorr: BIP-340 Schnorr signature scheme (secp256k1) - DEFAULT\n * - ECDSA: ECDSA signature scheme (secp256k1)\n * - Ed25519: RFC 8032 signatures\n * - Sr25519: Schnorr over Ristretto25519, used by Polkadot/Substrate\n * - MLDSA44: ML-DSA44 post-quantum signature scheme (NIST level 2)\n * - MLDSA65: ML-DSA65 post-quantum signature scheme (NIST level 3)\n * - MLDSA87: ML-DSA87 post-quantum signature scheme (NIST level 5)\n * - SshEd25519: Ed25519 via SSH agent\n * - SshDsa: DSA via SSH agent\n * - SshEcdsaP256: ECDSA P-256 via SSH agent\n * - SshEcdsaP384: ECDSA P-384 via SSH agent\n */\nexport enum SignatureScheme {\n /**\n * BIP-340 Schnorr signature scheme (secp256k1)\n * Default scheme (matching Rust bc-components default when secp256k1 is enabled)\n */\n Schnorr = \"Schnorr\",\n\n /**\n * ECDSA signature scheme (secp256k1)\n */\n Ecdsa = \"Ecdsa\",\n\n /**\n * Ed25519 signature scheme (RFC 8032)\n */\n Ed25519 = \"Ed25519\",\n\n /**\n * SR25519 signature scheme (Schnorr over Ristretto25519)\n * Used by Polkadot/Substrate\n */\n Sr25519 = \"Sr25519\",\n\n /**\n * ML-DSA44 post-quantum signature scheme (NIST level 2)\n */\n MLDSA44 = \"MLDSA44\",\n\n /**\n * ML-DSA65 post-quantum signature scheme (NIST level 3)\n */\n MLDSA65 = \"MLDSA65\",\n\n /**\n * ML-DSA87 post-quantum signature scheme (NIST level 5)\n */\n MLDSA87 = \"MLDSA87\",\n\n /**\n * Ed25519 signature via SSH agent.\n * Requires SSH agent daemon support.\n */\n SshEd25519 = \"SshEd25519\",\n\n /**\n * DSA signature via SSH agent.\n * Requires SSH agent daemon support.\n */\n SshDsa = \"SshDsa\",\n\n /**\n * ECDSA P-256 signature via SSH agent.\n * Requires SSH agent daemon support.\n */\n SshEcdsaP256 = \"SshEcdsaP256\",\n\n /**\n * ECDSA P-384 signature via SSH agent.\n * Requires SSH agent daemon support.\n */\n SshEcdsaP384 = \"SshEcdsaP384\",\n}\n\n/**\n * Get the default signature scheme.\n * Defaults to Schnorr (matching Rust bc-components default when secp256k1 is enabled).\n */\nexport function defaultSignatureScheme(): SignatureScheme {\n return SignatureScheme.Schnorr;\n}\n\n/**\n * Check if a signature scheme requires SSH agent support.\n *\n * @param scheme - The signature scheme to check\n * @returns true if the scheme requires SSH agent\n */\nexport function isSshScheme(scheme: SignatureScheme): boolean {\n return (\n scheme === SignatureScheme.SshEd25519 ||\n scheme === SignatureScheme.SshDsa ||\n scheme === SignatureScheme.SshEcdsaP256 ||\n scheme === SignatureScheme.SshEcdsaP384\n );\n}\n\n/**\n * Check if a signature scheme is a post-quantum ML-DSA scheme.\n *\n * @param scheme - The signature scheme to check\n * @returns true if the scheme is an ML-DSA scheme\n */\nexport function isMldsaScheme(scheme: SignatureScheme): boolean {\n return (\n scheme === SignatureScheme.MLDSA44 ||\n scheme === SignatureScheme.MLDSA65 ||\n scheme === SignatureScheme.MLDSA87\n );\n}\n\n/**\n * Options for configuring signature creation.\n *\n * Different signature schemes may require specific options:\n * - Schnorr: Optionally accepts a custom random number generator\n * - Ssh: Requires a namespace and hash algorithm\n *\n * Other signature types like ECDSA, Ed25519, Sr25519, and ML-DSA don't require options.\n */\nexport type SigningOptions =\n | {\n type: \"Schnorr\";\n /** Custom random number generator for signature creation */\n rng: RandomNumberGenerator;\n }\n | {\n type: \"Ssh\";\n /** The namespace used for SSH signatures */\n namespace: string;\n /** The hash algorithm used for SSH signatures */\n hashAlg: \"sha256\" | \"sha512\";\n };\n\n/**\n * Creates a new key pair for the signature scheme.\n *\n * @param scheme - The signature scheme to use\n * @returns A tuple containing a signing private key and its corresponding public key\n * @throws CryptoError for SSH-based schemes which require SSH agent support\n */\nexport function createKeypair(scheme: SignatureScheme): [SigningPrivateKey, SigningPublicKey] {\n switch (scheme) {\n case SignatureScheme.Schnorr: {\n const ecKey = ECPrivateKey.random();\n const privateKey = SigningPrivateKey.newSchnorr(ecKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.Ecdsa: {\n const ecKey = ECPrivateKey.random();\n const privateKey = SigningPrivateKey.newEcdsa(ecKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.Ed25519: {\n const ed25519Key = Ed25519PrivateKey.random();\n const privateKey = SigningPrivateKey.newEd25519(ed25519Key);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.Sr25519: {\n const sr25519Key = Sr25519PrivateKey.random();\n const privateKey = SigningPrivateKey.newSr25519(sr25519Key);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.MLDSA44: {\n const mldsaKey = MLDSAPrivateKey.new(MLDSALevel.MLDSA44);\n const privateKey = SigningPrivateKey.newMldsa(mldsaKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.MLDSA65: {\n const mldsaKey = MLDSAPrivateKey.new(MLDSALevel.MLDSA65);\n const privateKey = SigningPrivateKey.newMldsa(mldsaKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.MLDSA87: {\n const mldsaKey = MLDSAPrivateKey.new(MLDSALevel.MLDSA87);\n const privateKey = SigningPrivateKey.newMldsa(mldsaKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n throw CryptoError.sshAgent(\n `SSH signature scheme ${scheme} requires SSH agent support which is not yet implemented. ` +\n \"Use Ed25519, Sr25519, Schnorr, ECDSA, or MLDSA variants instead.\",\n );\n }\n}\n\n/**\n * Creates a new key pair for the signature scheme using a provided RNG.\n *\n * @param scheme - The signature scheme to use\n * @param rng - The random number generator to use\n * @returns A tuple containing a signing private key and its corresponding public key\n * @throws CryptoError for SSH-based schemes or MLDSA (which doesn't support deterministic generation)\n */\nexport function createKeypairUsing(\n scheme: SignatureScheme,\n rng: SecureRandomNumberGenerator,\n): [SigningPrivateKey, SigningPublicKey] {\n switch (scheme) {\n case SignatureScheme.Schnorr: {\n const ecKey = ECPrivateKey.newUsing(rng);\n const privateKey = SigningPrivateKey.newSchnorr(ecKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.Ecdsa: {\n const ecKey = ECPrivateKey.newUsing(rng);\n const privateKey = SigningPrivateKey.newEcdsa(ecKey);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.Ed25519: {\n const ed25519Key = Ed25519PrivateKey.randomUsing(rng);\n const privateKey = SigningPrivateKey.newEd25519(ed25519Key);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.Sr25519: {\n const sr25519Key = Sr25519PrivateKey.randomUsing(rng);\n const privateKey = SigningPrivateKey.newSr25519(sr25519Key);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n case SignatureScheme.MLDSA44:\n case SignatureScheme.MLDSA65:\n case SignatureScheme.MLDSA87:\n // ML-DSA doesn't support deterministic generation with custom RNG (matching Rust behavior)\n throw CryptoError.general(\n `Deterministic keypair generation not supported for ${scheme}. Use createKeypair() instead.`,\n );\n case SignatureScheme.SshEd25519:\n case SignatureScheme.SshDsa:\n case SignatureScheme.SshEcdsaP256:\n case SignatureScheme.SshEcdsaP384:\n throw CryptoError.sshAgent(\n `SSH signature scheme ${scheme} requires SSH agent support which is not yet implemented. ` +\n \"Use Ed25519, Sr25519, Schnorr, ECDSA, or MLDSA variants instead.\",\n );\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * MLKEM Security Level - ML-KEM (Module-Lattice-Based Key Encapsulation Mechanism)\n *\n * ML-KEM is a post-quantum key encapsulation mechanism standardized by NIST.\n * It provides three security levels corresponding to different NIST security categories.\n *\n * Security levels:\n * - MLKEM512: NIST Level 1 (equivalent to AES-128)\n * - MLKEM768: NIST Level 3 (equivalent to AES-192)\n * - MLKEM1024: NIST Level 5 (equivalent to AES-256)\n *\n * Ported from bc-components-rust/src/mlkem/mlkem_level.rs\n */\n\nimport { ml_kem512, ml_kem768, ml_kem1024 } from \"@noble/post-quantum/ml-kem.js\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\n\n/**\n * ML-KEM security levels.\n *\n * The numeric values correspond to the ML-KEM parameter set:\n * - 512: ML-KEM-512 (NIST Level 1)\n * - 768: ML-KEM-768 (NIST Level 3)\n * - 1024: ML-KEM-1024 (NIST Level 5)\n */\nexport enum MLKEMLevel {\n /** NIST Level 1 - AES-128 equivalent security */\n MLKEM512 = 512,\n /** NIST Level 3 - AES-192 equivalent security */\n MLKEM768 = 768,\n /** NIST Level 5 - AES-256 equivalent security */\n MLKEM1024 = 1024,\n}\n\n/**\n * Key sizes for each ML-KEM security level.\n */\nexport const MLKEM_KEY_SIZES = {\n [MLKEMLevel.MLKEM512]: {\n privateKey: 1632,\n publicKey: 800,\n ciphertext: 768,\n sharedSecret: 32,\n },\n [MLKEMLevel.MLKEM768]: {\n privateKey: 2400,\n publicKey: 1184,\n ciphertext: 1088,\n sharedSecret: 32,\n },\n [MLKEMLevel.MLKEM1024]: {\n privateKey: 3168,\n publicKey: 1568,\n ciphertext: 1568,\n sharedSecret: 32,\n },\n} as const;\n\n/**\n * Get the private key size for a given ML-KEM level.\n */\nexport function mlkemPrivateKeySize(level: MLKEMLevel): number {\n return MLKEM_KEY_SIZES[level].privateKey;\n}\n\n/**\n * Get the public key size for a given ML-KEM level.\n */\nexport function mlkemPublicKeySize(level: MLKEMLevel): number {\n return MLKEM_KEY_SIZES[level].publicKey;\n}\n\n/**\n * Get the ciphertext size for a given ML-KEM level.\n */\nexport function mlkemCiphertextSize(level: MLKEMLevel): number {\n return MLKEM_KEY_SIZES[level].ciphertext;\n}\n\n/**\n * Get the shared secret size for a given ML-KEM level.\n * Note: This is always 32 bytes for all ML-KEM levels.\n */\nexport function mlkemSharedSecretSize(level: MLKEMLevel): number {\n return MLKEM_KEY_SIZES[level].sharedSecret;\n}\n\n/**\n * Convert an ML-KEM level to its string representation.\n */\nexport function mlkemLevelToString(level: MLKEMLevel): string {\n switch (level) {\n case MLKEMLevel.MLKEM512:\n return \"MLKEM512\";\n case MLKEMLevel.MLKEM768:\n return \"MLKEM768\";\n case MLKEMLevel.MLKEM1024:\n return \"MLKEM1024\";\n }\n}\n\n/**\n * Parse an ML-KEM level from its numeric value.\n */\nexport function mlkemLevelFromValue(value: number): MLKEMLevel {\n switch (value) {\n case 512:\n return MLKEMLevel.MLKEM512;\n case 768:\n return MLKEMLevel.MLKEM768;\n case 1024:\n return MLKEMLevel.MLKEM1024;\n default:\n throw new Error(`Invalid MLKEM level value: ${value}`);\n }\n}\n\n/**\n * Internal type for ML-KEM keypair generation result.\n */\nexport interface MLKEMKeypairData {\n publicKey: Uint8Array;\n secretKey: Uint8Array;\n}\n\n/**\n * Internal type for ML-KEM encapsulation result.\n */\nexport interface MLKEMEncapsulationResult {\n sharedSecret: Uint8Array;\n ciphertext: Uint8Array;\n}\n\n/**\n * Generate an ML-KEM keypair for the given security level.\n *\n * @param level - The ML-KEM security level\n * @returns Object containing publicKey and secretKey bytes\n */\nexport function mlkemGenerateKeypair(level: MLKEMLevel): MLKEMKeypairData {\n const rng = new SecureRandomNumberGenerator();\n return mlkemGenerateKeypairUsing(level, rng);\n}\n\n/**\n * Generate an ML-KEM keypair using a provided RNG.\n *\n * @param level - The ML-KEM security level\n * @param rng - Random number generator\n * @returns Object containing publicKey and secretKey bytes\n */\nexport function mlkemGenerateKeypairUsing(\n level: MLKEMLevel,\n rng: RandomNumberGenerator,\n): MLKEMKeypairData {\n // Generate random seed for keypair generation\n const seed = rng.randomData(64);\n\n switch (level) {\n case MLKEMLevel.MLKEM512: {\n const keypair = ml_kem512.keygen(seed);\n return { publicKey: keypair.publicKey, secretKey: keypair.secretKey };\n }\n case MLKEMLevel.MLKEM768: {\n const keypair = ml_kem768.keygen(seed);\n return { publicKey: keypair.publicKey, secretKey: keypair.secretKey };\n }\n case MLKEMLevel.MLKEM1024: {\n const keypair = ml_kem1024.keygen(seed);\n return { publicKey: keypair.publicKey, secretKey: keypair.secretKey };\n }\n }\n}\n\n/**\n * Encapsulate a new shared secret using a public key.\n *\n * @param level - The ML-KEM security level\n * @param publicKey - The public key bytes\n * @returns Object containing sharedSecret and ciphertext bytes\n */\nexport function mlkemEncapsulate(\n level: MLKEMLevel,\n publicKey: Uint8Array,\n): MLKEMEncapsulationResult {\n switch (level) {\n case MLKEMLevel.MLKEM512: {\n const result = ml_kem512.encapsulate(publicKey);\n return { sharedSecret: result.sharedSecret, ciphertext: result.cipherText };\n }\n case MLKEMLevel.MLKEM768: {\n const result = ml_kem768.encapsulate(publicKey);\n return { sharedSecret: result.sharedSecret, ciphertext: result.cipherText };\n }\n case MLKEMLevel.MLKEM1024: {\n const result = ml_kem1024.encapsulate(publicKey);\n return { sharedSecret: result.sharedSecret, ciphertext: result.cipherText };\n }\n }\n}\n\n/**\n * Decapsulate a shared secret using a private key and ciphertext.\n *\n * @param level - The ML-KEM security level\n * @param secretKey - The secret key bytes\n * @param ciphertext - The ciphertext bytes\n * @returns The shared secret bytes\n */\nexport function mlkemDecapsulate(\n level: MLKEMLevel,\n secretKey: Uint8Array,\n ciphertext: Uint8Array,\n): Uint8Array {\n switch (level) {\n case MLKEMLevel.MLKEM512:\n return ml_kem512.decapsulate(ciphertext, secretKey);\n case MLKEMLevel.MLKEM768:\n return ml_kem768.decapsulate(ciphertext, secretKey);\n case MLKEMLevel.MLKEM1024:\n return ml_kem1024.decapsulate(ciphertext, secretKey);\n }\n}\n\n/**\n * Private key portion sizes for each ML-KEM level.\n * The decapsulation key structure is: dk = (dk_pke || ek_pke || H(ek) || z)\n * where dk_pke is the private portion before the public key.\n */\nconst MLKEM_DK_PKE_SIZES = {\n [MLKEMLevel.MLKEM512]: 768, // 12 * 64\n [MLKEMLevel.MLKEM768]: 1152, // 12 * 96\n [MLKEMLevel.MLKEM1024]: 1536, // 12 * 128\n} as const;\n\n/**\n * Extract the public key from a secret key.\n *\n * In ML-KEM (FIPS 203), the decapsulation key contains the encapsulation key (public key)\n * embedded within it. The structure is: dk = (dk_pke || ek_pke || H(ek) || z)\n *\n * @param level - The ML-KEM security level\n * @param secretKey - The secret key bytes\n * @returns The public key bytes extracted from the secret key\n */\nexport function mlkemExtractPublicKey(level: MLKEMLevel, secretKey: Uint8Array): Uint8Array {\n const dkPkeSize = MLKEM_DK_PKE_SIZES[level];\n const publicKeySize = MLKEM_KEY_SIZES[level].publicKey;\n const offset = dkPkeSize;\n return secretKey.slice(offset, offset + publicKeySize);\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * MLKEMCiphertext - ML-KEM Ciphertext for post-quantum key encapsulation\n *\n * MLKEMCiphertext wraps an ML-KEM ciphertext for transmission and decapsulation.\n * It supports all three security levels (MLKEM512, MLKEM768, MLKEM1024).\n *\n * # CBOR Serialization\n *\n * MLKEMCiphertext is serialized with tag 40102:\n * ```\n * #6.40102([level, h'<ciphertext-bytes>'])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `mlkem-ciphertext`\n *\n * Ported from bc-components-rust/src/mlkem/mlkem_ciphertext.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n expectInteger,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { MLKEM_CIPHERTEXT as TAG_MLKEM_CIPHERTEXT } from \"@bcts/tags\";\n\nimport {\n MLKEMLevel,\n mlkemLevelFromValue,\n mlkemLevelToString,\n mlkemCiphertextSize,\n} from \"./mlkem-level.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * MLKEMCiphertext - Post-quantum key encapsulation ciphertext using ML-KEM.\n */\nexport class MLKEMCiphertext\n implements CborTaggedEncodable, CborTaggedDecodable<MLKEMCiphertext>, UREncodable\n{\n private readonly _level: MLKEMLevel;\n private readonly _data: Uint8Array;\n\n private constructor(level: MLKEMLevel, data: Uint8Array) {\n const expectedSize = mlkemCiphertextSize(level);\n if (data.length !== expectedSize) {\n throw new Error(\n `MLKEMCiphertext (${mlkemLevelToString(level)}) must be ${expectedSize} bytes, got ${data.length}`,\n );\n }\n this._level = level;\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an MLKEMCiphertext from raw bytes.\n *\n * @param level - The ML-KEM security level\n * @param data - The ciphertext bytes\n */\n static fromBytes(level: MLKEMLevel, data: Uint8Array): MLKEMCiphertext {\n return new MLKEMCiphertext(level, data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the security level of this ciphertext.\n */\n level(): MLKEMLevel {\n return this._level;\n }\n\n /**\n * Returns the raw ciphertext bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw ciphertext bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the size of the ciphertext in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another MLKEMCiphertext.\n */\n equals(other: MLKEMCiphertext): boolean {\n if (this._level !== other._level) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `MLKEMCiphertext(${mlkemLevelToString(this._level)}, ${hex.substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with MLKEMCiphertext.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_MLKEM_CIPHERTEXT.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [level, ciphertext_bytes]\n */\n untaggedCbor(): Cbor {\n return cbor([this._level, this._data]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an MLKEMCiphertext by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): MLKEMCiphertext {\n const elements = expectArray(cborValue);\n if (elements.length !== 2) {\n throw new Error(`MLKEMCiphertext CBOR must have 2 elements, got ${elements.length}`);\n }\n const levelValue = Number(expectInteger(elements[0]));\n const level = mlkemLevelFromValue(levelValue);\n const data = expectBytes(elements[1]);\n return MLKEMCiphertext.fromBytes(level, data);\n }\n\n /**\n * Creates an MLKEMCiphertext by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): MLKEMCiphertext {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): MLKEMCiphertext {\n // Create a minimal dummy instance for decoding\n const dummyData = new Uint8Array(mlkemCiphertextSize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMCiphertext(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): MLKEMCiphertext {\n const cborValue = decodeCbor(data);\n return MLKEMCiphertext.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): MLKEMCiphertext {\n const cborValue = decodeCbor(data);\n const dummyData = new Uint8Array(mlkemCiphertextSize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMCiphertext(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_MLKEM_CIPHERTEXT.name;\n if (name === undefined) {\n throw new Error(\"MLKEM_CIPHERTEXT tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an MLKEMCiphertext from a UR.\n */\n static fromUR(ur: UR): MLKEMCiphertext {\n if (ur.urTypeStr() !== TAG_MLKEM_CIPHERTEXT.name) {\n throw new Error(`Expected UR type ${TAG_MLKEM_CIPHERTEXT.name}, got ${ur.urTypeStr()}`);\n }\n const dummyData = new Uint8Array(mlkemCiphertextSize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMCiphertext(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an MLKEMCiphertext from a UR string.\n */\n static fromURString(urString: string): MLKEMCiphertext {\n const ur = UR.fromURString(urString);\n return MLKEMCiphertext.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Encapsulation ciphertext for key encapsulation mechanisms\n *\n * This type represents the ciphertext produced during key encapsulation.\n * For X25519, this is actually an ephemeral public key used in ECDH.\n * For MLKEM, this is the ciphertext from the ML-KEM encapsulation.\n *\n * # CBOR Serialization\n *\n * For X25519, the ciphertext is serialized with the X25519 public key tag (40011).\n * For MLKEM, the ciphertext is serialized with tag 40102.\n *\n * Ported from bc-components-rust/src/encapsulation/encapsulation_ciphertext.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n tagValue,\n} from \"@bcts/dcbor\";\nimport {\n X25519_PUBLIC_KEY as TAG_X25519_PUBLIC_KEY,\n MLKEM_CIPHERTEXT as TAG_MLKEM_CIPHERTEXT,\n} from \"@bcts/tags\";\nimport { X25519PublicKey } from \"../x25519/x25519-public-key.js\";\nimport { EncapsulationScheme } from \"./encapsulation-scheme.js\";\nimport { MLKEMCiphertext } from \"../mlkem/mlkem-ciphertext.js\";\nimport { MLKEMLevel } from \"../mlkem/mlkem-level.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * Convert MLKEMLevel to EncapsulationScheme\n */\nfunction mlkemLevelToScheme(level: MLKEMLevel): EncapsulationScheme {\n switch (level) {\n case MLKEMLevel.MLKEM512:\n return EncapsulationScheme.MLKEM512;\n case MLKEMLevel.MLKEM768:\n return EncapsulationScheme.MLKEM768;\n case MLKEMLevel.MLKEM1024:\n return EncapsulationScheme.MLKEM1024;\n }\n}\n\n/**\n * Check if a scheme is an MLKEM scheme\n */\nfunction isMlkemScheme(scheme: EncapsulationScheme): boolean {\n return (\n scheme === EncapsulationScheme.MLKEM512 ||\n scheme === EncapsulationScheme.MLKEM768 ||\n scheme === EncapsulationScheme.MLKEM1024\n );\n}\n\n/**\n * Represents the ciphertext from a key encapsulation operation.\n *\n * For X25519, this wraps an ephemeral public key.\n * For MLKEM, this wraps an MLKEMCiphertext.\n */\nexport class EncapsulationCiphertext\n implements CborTaggedEncodable, CborTaggedDecodable<EncapsulationCiphertext>\n{\n private readonly _scheme: EncapsulationScheme;\n private readonly _x25519PublicKey: X25519PublicKey | undefined;\n private readonly _mlkemCiphertext: MLKEMCiphertext | undefined;\n\n private constructor(\n scheme: EncapsulationScheme,\n x25519PublicKey?: X25519PublicKey,\n mlkemCiphertext?: MLKEMCiphertext,\n ) {\n this._scheme = scheme;\n this._x25519PublicKey = x25519PublicKey;\n this._mlkemCiphertext = mlkemCiphertext;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an EncapsulationCiphertext from an X25519PublicKey.\n */\n static fromX25519PublicKey(publicKey: X25519PublicKey): EncapsulationCiphertext {\n return new EncapsulationCiphertext(EncapsulationScheme.X25519, publicKey, undefined);\n }\n\n /**\n * Create an EncapsulationCiphertext from raw X25519 data.\n */\n static fromX25519Data(data: Uint8Array): EncapsulationCiphertext {\n const publicKey = X25519PublicKey.fromDataRef(data);\n return EncapsulationCiphertext.fromX25519PublicKey(publicKey);\n }\n\n /**\n * Create an EncapsulationCiphertext from an MLKEMCiphertext.\n */\n static fromMlkem(ciphertext: MLKEMCiphertext): EncapsulationCiphertext {\n const scheme = mlkemLevelToScheme(ciphertext.level());\n return new EncapsulationCiphertext(scheme, undefined, ciphertext);\n }\n\n /**\n * Create an EncapsulationCiphertext from raw MLKEM ciphertext bytes.\n */\n static fromMlkemData(level: MLKEMLevel, data: Uint8Array): EncapsulationCiphertext {\n const ciphertext = MLKEMCiphertext.fromBytes(level, data);\n return EncapsulationCiphertext.fromMlkem(ciphertext);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the encapsulation scheme.\n */\n encapsulationScheme(): EncapsulationScheme {\n return this._scheme;\n }\n\n /**\n * Returns true if this is an X25519 ciphertext.\n */\n isX25519(): boolean {\n return this._scheme === EncapsulationScheme.X25519;\n }\n\n /**\n * Returns true if this is an MLKEM ciphertext.\n */\n isMlkem(): boolean {\n return isMlkemScheme(this._scheme);\n }\n\n /**\n * Returns the X25519 public key if this is an X25519 ciphertext.\n * @throws Error if this is not an X25519 ciphertext\n */\n x25519PublicKey(): X25519PublicKey {\n if (this._x25519PublicKey === undefined) {\n throw new Error(\"Not an X25519 ciphertext\");\n }\n return this._x25519PublicKey;\n }\n\n /**\n * Returns the MLKEM ciphertext if this is an MLKEM ciphertext.\n * @throws Error if this is not an MLKEM ciphertext\n */\n mlkemCiphertext(): MLKEMCiphertext {\n if (this._mlkemCiphertext === undefined) {\n throw new Error(\"Not an MLKEM ciphertext\");\n }\n return this._mlkemCiphertext;\n }\n\n /**\n * Returns the X25519 public key if available, or null.\n */\n toX25519(): X25519PublicKey | null {\n return this._x25519PublicKey ?? null;\n }\n\n /**\n * Returns the MLKEM ciphertext if available, or null.\n */\n toMlkem(): MLKEMCiphertext | null {\n return this._mlkemCiphertext ?? null;\n }\n\n /**\n * Returns the raw ciphertext data.\n */\n data(): Uint8Array {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PublicKey;\n if (pk === undefined) throw new Error(\"X25519 public key not set\");\n return pk.data();\n } else if (isMlkemScheme(this._scheme)) {\n const ct = this._mlkemCiphertext;\n if (ct === undefined) throw new Error(\"MLKEM ciphertext not set\");\n return ct.data();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Compare with another EncapsulationCiphertext.\n */\n equals(other: EncapsulationCiphertext): boolean {\n if (this._scheme !== other._scheme) return false;\n if (this._scheme === EncapsulationScheme.X25519) {\n const thisPk = this._x25519PublicKey;\n const otherPk = other._x25519PublicKey;\n if (thisPk === undefined || otherPk === undefined) return false;\n return thisPk.equals(otherPk);\n } else if (isMlkemScheme(this._scheme)) {\n const thisCt = this._mlkemCiphertext;\n const otherCt = other._mlkemCiphertext;\n if (thisCt === undefined || otherCt === undefined) return false;\n return thisCt.equals(otherCt);\n }\n return false;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n if (this._scheme === EncapsulationScheme.X25519) {\n return `EncapsulationCiphertext(X25519, ${bytesToHex(this.data()).substring(0, 16)}...)`;\n } else if (isMlkemScheme(this._scheme)) {\n return `EncapsulationCiphertext(${String(this._scheme)}, ${bytesToHex(this.data()).substring(0, 16)}...)`;\n }\n return `EncapsulationCiphertext(${String(this._scheme)})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with this ciphertext.\n */\n cborTags(): Tag[] {\n if (this._scheme === EncapsulationScheme.X25519) {\n return tagsForValues([TAG_X25519_PUBLIC_KEY.value]);\n } else if (isMlkemScheme(this._scheme)) {\n return tagsForValues([TAG_MLKEM_CIPHERTEXT.value]);\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n */\n untaggedCbor(): Cbor {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PublicKey;\n if (pk === undefined) throw new Error(\"X25519 public key not set\");\n return toByteString(pk.data());\n } else if (isMlkemScheme(this._scheme)) {\n const ct = this._mlkemCiphertext;\n if (ct === undefined) throw new Error(\"MLKEM ciphertext not set\");\n return ct.untaggedCbor();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an EncapsulationCiphertext by decoding it from untagged CBOR.\n * Note: Without tags, we assume X25519 scheme.\n */\n fromUntaggedCbor(cborValue: Cbor): EncapsulationCiphertext {\n const data = expectBytes(cborValue);\n const publicKey = X25519PublicKey.fromDataRef(data);\n return EncapsulationCiphertext.fromX25519PublicKey(publicKey);\n }\n\n /**\n * Creates an EncapsulationCiphertext by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): EncapsulationCiphertext {\n const tag = tagValue(cborValue);\n\n if (tag === TAG_X25519_PUBLIC_KEY.value) {\n const content = extractTaggedContent(cborValue);\n const data = expectBytes(content);\n const publicKey = X25519PublicKey.fromDataRef(data);\n return EncapsulationCiphertext.fromX25519PublicKey(publicKey);\n }\n\n if (tag === TAG_MLKEM_CIPHERTEXT.value) {\n const mlkemCiphertext = MLKEMCiphertext.fromTaggedCbor(cborValue);\n return EncapsulationCiphertext.fromMlkem(mlkemCiphertext);\n }\n\n throw new Error(`Unknown ciphertext tag: ${tag}`);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): EncapsulationCiphertext {\n const dummy = EncapsulationCiphertext.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): EncapsulationCiphertext {\n const cborValue = decodeCbor(data);\n return EncapsulationCiphertext.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): EncapsulationCiphertext {\n const cborValue = decodeCbor(data);\n const dummy = EncapsulationCiphertext.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromUntaggedCbor(cborValue);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * MLKEMPublicKey - ML-KEM Public Key for post-quantum key encapsulation\n *\n * MLKEMPublicKey wraps an ML-KEM public key for encapsulating shared secrets.\n * It supports all three security levels (MLKEM512, MLKEM768, MLKEM1024).\n *\n * # CBOR Serialization\n *\n * MLKEMPublicKey is serialized with tag 40101:\n * ```\n * #6.40101([level, h'<public-key-bytes>'])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `mlkem-public-key`\n *\n * Ported from bc-components-rust/src/mlkem/mlkem_public_key.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n expectInteger,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { MLKEM_PUBLIC_KEY as TAG_MLKEM_PUBLIC_KEY } from \"@bcts/tags\";\n\nimport {\n MLKEMLevel,\n mlkemLevelFromValue,\n mlkemLevelToString,\n mlkemPublicKeySize,\n mlkemEncapsulate,\n} from \"./mlkem-level.js\";\nimport { MLKEMCiphertext } from \"./mlkem-ciphertext.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * Result of encapsulation operation.\n */\nexport interface MLKEMEncapsulationPair {\n /** The shared secret as a SymmetricKey */\n sharedSecret: SymmetricKey;\n /** The ciphertext to send to the private key holder */\n ciphertext: MLKEMCiphertext;\n}\n\n/**\n * MLKEMPublicKey - Post-quantum key encapsulation public key using ML-KEM.\n */\nexport class MLKEMPublicKey\n implements CborTaggedEncodable, CborTaggedDecodable<MLKEMPublicKey>, UREncodable\n{\n private readonly _level: MLKEMLevel;\n private readonly _data: Uint8Array;\n\n private constructor(level: MLKEMLevel, data: Uint8Array) {\n const expectedSize = mlkemPublicKeySize(level);\n if (data.length !== expectedSize) {\n throw new Error(\n `MLKEMPublicKey (${mlkemLevelToString(level)}) must be ${expectedSize} bytes, got ${data.length}`,\n );\n }\n this._level = level;\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an MLKEMPublicKey from raw bytes.\n *\n * @param level - The ML-KEM security level\n * @param data - The public key bytes\n */\n static fromBytes(level: MLKEMLevel, data: Uint8Array): MLKEMPublicKey {\n return new MLKEMPublicKey(level, data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the security level of this key.\n */\n level(): MLKEMLevel {\n return this._level;\n }\n\n /**\n * Returns the raw key bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw key bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the size of the key in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n /**\n * Encapsulate a new shared secret.\n *\n * This creates a random shared secret and encapsulates it, returning both\n * the shared secret (to be used as a symmetric key) and the ciphertext\n * (to be sent to the private key holder for decapsulation).\n *\n * @returns Object containing sharedSecret and ciphertext\n */\n encapsulate(): MLKEMEncapsulationPair {\n const result = mlkemEncapsulate(this._level, this._data);\n const sharedSecret = SymmetricKey.fromData(result.sharedSecret);\n const ciphertext = MLKEMCiphertext.fromBytes(this._level, result.ciphertext);\n return { sharedSecret, ciphertext };\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another MLKEMPublicKey.\n */\n equals(other: MLKEMPublicKey): boolean {\n if (this._level !== other._level) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `MLKEMPublicKey(${mlkemLevelToString(this._level)}, ${hex.substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with MLKEMPublicKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_MLKEM_PUBLIC_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [level, key_bytes]\n */\n untaggedCbor(): Cbor {\n return cbor([this._level, this._data]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an MLKEMPublicKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): MLKEMPublicKey {\n const elements = expectArray(cborValue);\n if (elements.length !== 2) {\n throw new Error(`MLKEMPublicKey CBOR must have 2 elements, got ${elements.length}`);\n }\n const levelValue = Number(expectInteger(elements[0]));\n const level = mlkemLevelFromValue(levelValue);\n const data = expectBytes(elements[1]);\n return MLKEMPublicKey.fromBytes(level, data);\n }\n\n /**\n * Creates an MLKEMPublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): MLKEMPublicKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): MLKEMPublicKey {\n // Create a minimal dummy instance for decoding\n const dummyData = new Uint8Array(mlkemPublicKeySize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMPublicKey(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): MLKEMPublicKey {\n const cborValue = decodeCbor(data);\n return MLKEMPublicKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): MLKEMPublicKey {\n const cborValue = decodeCbor(data);\n const dummyData = new Uint8Array(mlkemPublicKeySize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMPublicKey(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_MLKEM_PUBLIC_KEY.name;\n if (name === undefined) {\n throw new Error(\"MLKEM_PUBLIC_KEY tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an MLKEMPublicKey from a UR.\n */\n static fromUR(ur: UR): MLKEMPublicKey {\n if (ur.urTypeStr() !== TAG_MLKEM_PUBLIC_KEY.name) {\n throw new Error(`Expected UR type ${TAG_MLKEM_PUBLIC_KEY.name}, got ${ur.urTypeStr()}`);\n }\n const dummyData = new Uint8Array(mlkemPublicKeySize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMPublicKey(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an MLKEMPublicKey from a UR string.\n */\n static fromURString(urString: string): MLKEMPublicKey {\n const ur = UR.fromURString(urString);\n return MLKEMPublicKey.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Encapsulation public key for key encapsulation mechanisms\n *\n * This type represents a public key that can be used to encapsulate (encrypt)\n * a shared secret. The recipient can then use their corresponding private key\n * to decapsulate (decrypt) the shared secret.\n *\n * For X25519, encapsulation works by:\n * 1. Generating an ephemeral key pair\n * 2. Performing ECDH with the ephemeral private key and the recipient's public key\n * 3. Returning the shared secret and the ephemeral public key as \"ciphertext\"\n *\n * For MLKEM, encapsulation uses the ML-KEM algorithm to generate a shared secret\n * and ciphertext.\n *\n * # CBOR Serialization\n *\n * For X25519, the public key is serialized with tag 40011.\n * For MLKEM, the public key is serialized with tag 40101.\n *\n * Ported from bc-components-rust/src/encapsulation/encapsulation_public_key.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n tagValue,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport {\n X25519_PUBLIC_KEY as TAG_X25519_PUBLIC_KEY,\n MLKEM_PUBLIC_KEY as TAG_MLKEM_PUBLIC_KEY,\n} from \"@bcts/tags\";\nimport { X25519PrivateKey } from \"../x25519/x25519-private-key.js\";\nimport { X25519PublicKey } from \"../x25519/x25519-public-key.js\";\nimport { type SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { EncapsulationScheme } from \"./encapsulation-scheme.js\";\nimport { EncapsulationCiphertext } from \"./encapsulation-ciphertext.js\";\nimport { MLKEMPublicKey } from \"../mlkem/mlkem-public-key.js\";\nimport { MLKEMLevel } from \"../mlkem/mlkem-level.js\";\nimport { bytesToHex } from \"../utils.js\";\nimport { Reference, type ReferenceProvider } from \"../reference.js\";\nimport { Digest } from \"../digest.js\";\n\n/**\n * Convert MLKEMLevel to EncapsulationScheme\n */\nfunction mlkemLevelToScheme(level: MLKEMLevel): EncapsulationScheme {\n switch (level) {\n case MLKEMLevel.MLKEM512:\n return EncapsulationScheme.MLKEM512;\n case MLKEMLevel.MLKEM768:\n return EncapsulationScheme.MLKEM768;\n case MLKEMLevel.MLKEM1024:\n return EncapsulationScheme.MLKEM1024;\n }\n}\n\n/**\n * Check if a scheme is an MLKEM scheme\n */\nfunction isMlkemScheme(scheme: EncapsulationScheme): boolean {\n return (\n scheme === EncapsulationScheme.MLKEM512 ||\n scheme === EncapsulationScheme.MLKEM768 ||\n scheme === EncapsulationScheme.MLKEM1024\n );\n}\n\n/**\n * Represents a public key for key encapsulation.\n *\n * Use this to encapsulate a shared secret for a recipient.\n */\nexport class EncapsulationPublicKey\n implements\n ReferenceProvider,\n CborTaggedEncodable,\n CborTaggedDecodable<EncapsulationPublicKey>,\n UREncodable\n{\n private readonly _scheme: EncapsulationScheme;\n private readonly _x25519PublicKey: X25519PublicKey | undefined;\n private readonly _mlkemPublicKey: MLKEMPublicKey | undefined;\n\n private constructor(\n scheme: EncapsulationScheme,\n x25519PublicKey?: X25519PublicKey,\n mlkemPublicKey?: MLKEMPublicKey,\n ) {\n this._scheme = scheme;\n this._x25519PublicKey = x25519PublicKey;\n this._mlkemPublicKey = mlkemPublicKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an EncapsulationPublicKey from an X25519PublicKey.\n */\n static fromX25519PublicKey(publicKey: X25519PublicKey): EncapsulationPublicKey {\n return new EncapsulationPublicKey(EncapsulationScheme.X25519, publicKey, undefined);\n }\n\n /**\n * Create an EncapsulationPublicKey from raw X25519 public key bytes.\n */\n static fromX25519Data(data: Uint8Array): EncapsulationPublicKey {\n const publicKey = X25519PublicKey.fromDataRef(data);\n return EncapsulationPublicKey.fromX25519PublicKey(publicKey);\n }\n\n /**\n * Create an EncapsulationPublicKey from an MLKEMPublicKey.\n */\n static fromMlkem(publicKey: MLKEMPublicKey): EncapsulationPublicKey {\n const scheme = mlkemLevelToScheme(publicKey.level());\n return new EncapsulationPublicKey(scheme, undefined, publicKey);\n }\n\n /**\n * Create an EncapsulationPublicKey from raw MLKEM public key bytes.\n */\n static fromMlkemData(level: MLKEMLevel, data: Uint8Array): EncapsulationPublicKey {\n const publicKey = MLKEMPublicKey.fromBytes(level, data);\n return EncapsulationPublicKey.fromMlkem(publicKey);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the encapsulation scheme.\n */\n encapsulationScheme(): EncapsulationScheme {\n return this._scheme;\n }\n\n /**\n * Returns true if this is an X25519 public key.\n */\n isX25519(): boolean {\n return this._scheme === EncapsulationScheme.X25519;\n }\n\n /**\n * Returns true if this is an MLKEM public key.\n */\n isMlkem(): boolean {\n return isMlkemScheme(this._scheme);\n }\n\n /**\n * Returns the X25519 public key if this is an X25519 encapsulation key.\n * @throws Error if this is not an X25519 key\n */\n x25519PublicKey(): X25519PublicKey {\n if (this._x25519PublicKey === undefined) {\n throw new Error(\"Not an X25519 public key\");\n }\n return this._x25519PublicKey;\n }\n\n /**\n * Returns the MLKEM public key if this is an MLKEM encapsulation key.\n * @throws Error if this is not an MLKEM key\n */\n mlkemPublicKey(): MLKEMPublicKey {\n if (this._mlkemPublicKey === undefined) {\n throw new Error(\"Not an MLKEM public key\");\n }\n return this._mlkemPublicKey;\n }\n\n /**\n * Returns the X25519 public key if available, or null.\n */\n toX25519(): X25519PublicKey | null {\n return this._x25519PublicKey ?? null;\n }\n\n /**\n * Returns the MLKEM public key if available, or null.\n */\n toMlkem(): MLKEMPublicKey | null {\n return this._mlkemPublicKey ?? null;\n }\n\n /**\n * Returns the raw public key data.\n */\n data(): Uint8Array {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PublicKey;\n if (pk === undefined) throw new Error(\"X25519 public key not set\");\n return pk.data();\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPublicKey;\n if (pk === undefined) throw new Error(\"MLKEM public key not set\");\n return pk.data();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns this object as an EncapsulationPublicKey.\n *\n * This method allows EncapsulationPublicKey to implement the Encrypter interface.\n * Since this class is itself an encapsulation public key, it returns `this`.\n *\n * @returns This encapsulation public key\n */\n encapsulationPublicKey(): EncapsulationPublicKey {\n return this;\n }\n\n /**\n * Encapsulate a new shared secret for this public key.\n *\n * This generates a random shared secret and encapsulates it so that only\n * the holder of the corresponding private key can recover it.\n *\n * @returns A tuple of [sharedSecret, ciphertext]\n */\n encapsulateNewSharedSecret(): [SymmetricKey, EncapsulationCiphertext] {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PublicKey;\n if (pk === undefined) throw new Error(\"X25519 public key not set\");\n // Generate ephemeral key pair\n const [ephemeralPrivate, ephemeralPublic] = X25519PrivateKey.keypair();\n\n // Perform ECDH to get shared secret\n const sharedSecret = ephemeralPrivate.sharedKeyWith(pk);\n\n // The \"ciphertext\" is the ephemeral public key\n const ciphertext = EncapsulationCiphertext.fromX25519PublicKey(ephemeralPublic);\n\n return [sharedSecret, ciphertext];\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPublicKey;\n if (pk === undefined) throw new Error(\"MLKEM public key not set\");\n\n // Encapsulate using MLKEM\n const { sharedSecret, ciphertext: mlkemCiphertext } = pk.encapsulate();\n\n // Wrap in EncapsulationCiphertext\n const ciphertext = EncapsulationCiphertext.fromMlkem(mlkemCiphertext);\n\n return [sharedSecret, ciphertext];\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Compare with another EncapsulationPublicKey.\n */\n equals(other: EncapsulationPublicKey): boolean {\n if (this._scheme !== other._scheme) return false;\n if (this._scheme === EncapsulationScheme.X25519) {\n const thisPk = this._x25519PublicKey;\n const otherPk = other._x25519PublicKey;\n if (thisPk === undefined || otherPk === undefined) return false;\n return thisPk.equals(otherPk);\n } else if (isMlkemScheme(this._scheme)) {\n const thisPk = this._mlkemPublicKey;\n const otherPk = other._mlkemPublicKey;\n if (thisPk === undefined || otherPk === undefined) return false;\n return thisPk.equals(otherPk);\n }\n return false;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n if (this._scheme === EncapsulationScheme.X25519) {\n return `EncapsulationPublicKey(X25519, ${bytesToHex(this.data()).substring(0, 16)}...)`;\n } else if (isMlkemScheme(this._scheme)) {\n return `EncapsulationPublicKey(${String(this._scheme)}, ${bytesToHex(this.data()).substring(0, 16)}...)`;\n }\n return `EncapsulationPublicKey(${String(this._scheme)})`;\n }\n\n // ============================================================================\n // ReferenceProvider Interface\n // ============================================================================\n\n /**\n * Returns a unique reference to this EncapsulationPublicKey instance.\n *\n * The reference is derived from the SHA-256 hash of the tagged CBOR\n * representation, providing a unique, content-addressable identifier.\n */\n reference(): Reference {\n const digest = Digest.fromImage(this.taggedCborData());\n return Reference.from(digest);\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with this public key.\n */\n cborTags(): Tag[] {\n if (this._scheme === EncapsulationScheme.X25519) {\n return tagsForValues([TAG_X25519_PUBLIC_KEY.value]);\n } else if (isMlkemScheme(this._scheme)) {\n return tagsForValues([TAG_MLKEM_PUBLIC_KEY.value]);\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n */\n untaggedCbor(): Cbor {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PublicKey;\n if (pk === undefined) throw new Error(\"X25519 public key not set\");\n return toByteString(pk.data());\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPublicKey;\n if (pk === undefined) throw new Error(\"MLKEM public key not set\");\n return pk.untaggedCbor();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an EncapsulationPublicKey by decoding it from untagged CBOR.\n * Note: Without tags, we assume X25519 scheme.\n */\n fromUntaggedCbor(cborValue: Cbor): EncapsulationPublicKey {\n const data = expectBytes(cborValue);\n const publicKey = X25519PublicKey.fromDataRef(data);\n return EncapsulationPublicKey.fromX25519PublicKey(publicKey);\n }\n\n /**\n * Creates an EncapsulationPublicKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): EncapsulationPublicKey {\n const tag = tagValue(cborValue);\n\n if (tag === TAG_X25519_PUBLIC_KEY.value) {\n const content = extractTaggedContent(cborValue);\n const data = expectBytes(content);\n const publicKey = X25519PublicKey.fromDataRef(data);\n return EncapsulationPublicKey.fromX25519PublicKey(publicKey);\n }\n\n if (tag === TAG_MLKEM_PUBLIC_KEY.value) {\n const mlkemPublic = MLKEMPublicKey.fromTaggedCbor(cborValue);\n return EncapsulationPublicKey.fromMlkem(mlkemPublic);\n }\n\n throw new Error(`Unknown public key tag: ${tag}`);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): EncapsulationPublicKey {\n const dummy = EncapsulationPublicKey.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): EncapsulationPublicKey {\n const cborValue = decodeCbor(data);\n return EncapsulationPublicKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): EncapsulationPublicKey {\n const cborValue = decodeCbor(data);\n const dummy = EncapsulationPublicKey.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n if (this._scheme === EncapsulationScheme.X25519) {\n const name = TAG_X25519_PUBLIC_KEY.name;\n if (name === undefined) throw new Error(\"TAG_X25519_PUBLIC_KEY.name is undefined\");\n return UR.new(name, this.untaggedCbor());\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPublicKey;\n if (pk === undefined) throw new Error(\"MLKEM public key not set\");\n return pk.ur();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an EncapsulationPublicKey from a UR.\n */\n static fromUR(ur: UR): EncapsulationPublicKey {\n // Check for known UR types\n if (ur.urTypeStr() === TAG_X25519_PUBLIC_KEY.name) {\n const dummy = EncapsulationPublicKey.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n if (ur.urTypeStr() === TAG_MLKEM_PUBLIC_KEY.name) {\n const mlkemPublic = MLKEMPublicKey.fromUR(ur);\n return EncapsulationPublicKey.fromMlkem(mlkemPublic);\n }\n\n throw new Error(`Unknown UR type for EncapsulationPublicKey: ${ur.urTypeStr()}`);\n }\n\n /**\n * Creates an EncapsulationPublicKey from a UR string.\n */\n static fromURString(urString: string): EncapsulationPublicKey {\n const ur = UR.fromURString(urString);\n return EncapsulationPublicKey.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * MLKEMPrivateKey - ML-KEM Private Key for post-quantum key decapsulation\n *\n * MLKEMPrivateKey wraps an ML-KEM secret key for decapsulating shared secrets.\n * It supports all three security levels (MLKEM512, MLKEM768, MLKEM1024).\n *\n * # CBOR Serialization\n *\n * MLKEMPrivateKey is serialized with tag 40100:\n * ```\n * #6.40100([level, h'<private-key-bytes>'])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `mlkem-private-key`\n *\n * Ported from bc-components-rust/src/mlkem/mlkem_private_key.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n expectInteger,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { MLKEM_PRIVATE_KEY as TAG_MLKEM_PRIVATE_KEY } from \"@bcts/tags\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { SecureRandomNumberGenerator } from \"@bcts/rand\";\n\nimport {\n MLKEMLevel,\n mlkemLevelFromValue,\n mlkemLevelToString,\n mlkemPrivateKeySize,\n mlkemGenerateKeypairUsing,\n mlkemDecapsulate,\n mlkemExtractPublicKey,\n} from \"./mlkem-level.js\";\nimport { MLKEMPublicKey } from \"./mlkem-public-key.js\";\nimport type { MLKEMCiphertext } from \"./mlkem-ciphertext.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * MLKEMPrivateKey - Post-quantum key decapsulation private key using ML-KEM.\n */\nexport class MLKEMPrivateKey\n implements CborTaggedEncodable, CborTaggedDecodable<MLKEMPrivateKey>, UREncodable\n{\n private readonly _level: MLKEMLevel;\n private readonly _data: Uint8Array;\n\n private constructor(level: MLKEMLevel, data: Uint8Array) {\n const expectedSize = mlkemPrivateKeySize(level);\n if (data.length !== expectedSize) {\n throw new Error(\n `MLKEMPrivateKey (${mlkemLevelToString(level)}) must be ${expectedSize} bytes, got ${data.length}`,\n );\n }\n this._level = level;\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Generate a new random MLKEMPrivateKey with the specified security level.\n *\n * @param level - The ML-KEM security level (default: MLKEM768)\n */\n static new(level: MLKEMLevel = MLKEMLevel.MLKEM768): MLKEMPrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return MLKEMPrivateKey.newUsing(level, rng);\n }\n\n /**\n * Generate a new random MLKEMPrivateKey using the provided RNG.\n *\n * @param level - The ML-KEM security level\n * @param rng - Random number generator\n */\n static newUsing(level: MLKEMLevel, rng: RandomNumberGenerator): MLKEMPrivateKey {\n const keypair = mlkemGenerateKeypairUsing(level, rng);\n return new MLKEMPrivateKey(level, keypair.secretKey);\n }\n\n /**\n * Create an MLKEMPrivateKey from raw bytes.\n *\n * @param level - The ML-KEM security level\n * @param data - The private key bytes\n */\n static fromBytes(level: MLKEMLevel, data: Uint8Array): MLKEMPrivateKey {\n return new MLKEMPrivateKey(level, data);\n }\n\n /**\n * Generate a keypair and return both private and public keys.\n *\n * @param level - The ML-KEM security level (default: MLKEM768)\n * @returns Tuple of [privateKey, publicKey]\n */\n static keypair(level: MLKEMLevel = MLKEMLevel.MLKEM768): [MLKEMPrivateKey, MLKEMPublicKey] {\n const rng = new SecureRandomNumberGenerator();\n return MLKEMPrivateKey.keypairUsing(level, rng);\n }\n\n /**\n * Generate a keypair using the provided RNG.\n *\n * @param level - The ML-KEM security level\n * @param rng - Random number generator\n * @returns Tuple of [privateKey, publicKey]\n */\n static keypairUsing(\n level: MLKEMLevel,\n rng: RandomNumberGenerator,\n ): [MLKEMPrivateKey, MLKEMPublicKey] {\n const keypairData = mlkemGenerateKeypairUsing(level, rng);\n const privateKey = new MLKEMPrivateKey(level, keypairData.secretKey);\n const publicKey = MLKEMPublicKey.fromBytes(level, keypairData.publicKey);\n return [privateKey, publicKey];\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the security level of this key.\n */\n level(): MLKEMLevel {\n return this._level;\n }\n\n /**\n * Returns the raw key bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw key bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the size of the key in bytes.\n */\n size(): number {\n return this._data.length;\n }\n\n /**\n * Decapsulate a shared secret from a ciphertext.\n *\n * @param ciphertext - The ML-KEM ciphertext\n * @returns The decapsulated shared secret as a SymmetricKey\n */\n decapsulate(ciphertext: MLKEMCiphertext): SymmetricKey {\n if (ciphertext.level() !== this._level) {\n throw new Error(\n `Ciphertext level (${mlkemLevelToString(ciphertext.level())}) does not match key level (${mlkemLevelToString(this._level)})`,\n );\n }\n const sharedSecret = mlkemDecapsulate(this._level, this._data, ciphertext.asBytes());\n return SymmetricKey.fromData(sharedSecret);\n }\n\n /**\n * Derives and returns the corresponding public key.\n *\n * In ML-KEM (FIPS 203), the decapsulation key contains the encapsulation key (public key)\n * embedded within it. This method extracts that public key.\n *\n * @returns The corresponding MLKEMPublicKey\n */\n publicKey(): MLKEMPublicKey {\n const publicKeyData = mlkemExtractPublicKey(this._level, this._data);\n return MLKEMPublicKey.fromBytes(this._level, publicKeyData);\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another MLKEMPrivateKey.\n */\n equals(other: MLKEMPrivateKey): boolean {\n if (this._level !== other._level) return false;\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation (truncated for security).\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `MLKEMPrivateKey(${mlkemLevelToString(this._level)}, ${hex.substring(0, 8)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with MLKEMPrivateKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_MLKEM_PRIVATE_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [level, key_bytes]\n */\n untaggedCbor(): Cbor {\n return cbor([this._level, this._data]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an MLKEMPrivateKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): MLKEMPrivateKey {\n const elements = expectArray(cborValue);\n if (elements.length !== 2) {\n throw new Error(`MLKEMPrivateKey CBOR must have 2 elements, got ${elements.length}`);\n }\n const levelValue = Number(expectInteger(elements[0]));\n const level = mlkemLevelFromValue(levelValue);\n const data = expectBytes(elements[1]);\n return MLKEMPrivateKey.fromBytes(level, data);\n }\n\n /**\n * Creates an MLKEMPrivateKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): MLKEMPrivateKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): MLKEMPrivateKey {\n // Create a minimal dummy instance for decoding\n const dummyData = new Uint8Array(mlkemPrivateKeySize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMPrivateKey(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): MLKEMPrivateKey {\n const cborValue = decodeCbor(data);\n return MLKEMPrivateKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): MLKEMPrivateKey {\n const cborValue = decodeCbor(data);\n const dummyData = new Uint8Array(mlkemPrivateKeySize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMPrivateKey(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_MLKEM_PRIVATE_KEY.name;\n if (name === undefined) {\n throw new Error(\"MLKEM_PRIVATE_KEY tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an MLKEMPrivateKey from a UR.\n */\n static fromUR(ur: UR): MLKEMPrivateKey {\n if (ur.urTypeStr() !== TAG_MLKEM_PRIVATE_KEY.name) {\n throw new Error(`Expected UR type ${TAG_MLKEM_PRIVATE_KEY.name}, got ${ur.urTypeStr()}`);\n }\n const dummyData = new Uint8Array(mlkemPrivateKeySize(MLKEMLevel.MLKEM512));\n const dummy = new MLKEMPrivateKey(MLKEMLevel.MLKEM512, dummyData);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates an MLKEMPrivateKey from a UR string.\n */\n static fromURString(urString: string): MLKEMPrivateKey {\n const ur = UR.fromURString(urString);\n return MLKEMPrivateKey.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Encapsulation private key for key encapsulation mechanisms\n *\n * This type represents a private key that can be used to decapsulate (decrypt)\n * a shared secret that was encapsulated using the corresponding public key.\n *\n * For X25519, decapsulation works by:\n * 1. Receiving the ephemeral public key (ciphertext)\n * 2. Performing ECDH with the private key and the ephemeral public key\n * 3. Returning the shared secret\n *\n * For MLKEM, decapsulation uses the ML-KEM algorithm to recover the shared secret.\n *\n * # CBOR Serialization\n *\n * For X25519, the private key is serialized with tag 40010.\n * For MLKEM, the private key is serialized with tag 40100.\n *\n * Ported from bc-components-rust/src/encapsulation/encapsulation_private_key.rs\n */\n\nimport { SecureRandomNumberGenerator, type RandomNumberGenerator } from \"@bcts/rand\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n tagValue,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport {\n X25519_PRIVATE_KEY as TAG_X25519_PRIVATE_KEY,\n MLKEM_PRIVATE_KEY as TAG_MLKEM_PRIVATE_KEY,\n} from \"@bcts/tags\";\nimport { X25519PrivateKey } from \"../x25519/x25519-private-key.js\";\nimport { type SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { EncapsulationScheme } from \"./encapsulation-scheme.js\";\nimport { type EncapsulationCiphertext } from \"./encapsulation-ciphertext.js\";\nimport { EncapsulationPublicKey } from \"./encapsulation-public-key.js\";\nimport { MLKEMPrivateKey } from \"../mlkem/mlkem-private-key.js\";\nimport { MLKEMLevel } from \"../mlkem/mlkem-level.js\";\nimport { CryptoError } from \"../error.js\";\nimport { bytesToHex } from \"../utils.js\";\nimport { Reference, type ReferenceProvider } from \"../reference.js\";\nimport { Digest } from \"../digest.js\";\n\n/**\n * Convert MLKEMLevel to EncapsulationScheme\n */\nfunction mlkemLevelToScheme(level: MLKEMLevel): EncapsulationScheme {\n switch (level) {\n case MLKEMLevel.MLKEM512:\n return EncapsulationScheme.MLKEM512;\n case MLKEMLevel.MLKEM768:\n return EncapsulationScheme.MLKEM768;\n case MLKEMLevel.MLKEM1024:\n return EncapsulationScheme.MLKEM1024;\n }\n}\n\n/**\n * Check if a scheme is an MLKEM scheme\n */\nfunction isMlkemScheme(scheme: EncapsulationScheme): boolean {\n return (\n scheme === EncapsulationScheme.MLKEM512 ||\n scheme === EncapsulationScheme.MLKEM768 ||\n scheme === EncapsulationScheme.MLKEM1024\n );\n}\n\n/**\n * Represents a private key for key encapsulation.\n *\n * Use this to decapsulate a shared secret from ciphertext.\n */\nexport class EncapsulationPrivateKey\n implements\n ReferenceProvider,\n CborTaggedEncodable,\n CborTaggedDecodable<EncapsulationPrivateKey>,\n UREncodable\n{\n private readonly _scheme: EncapsulationScheme;\n private readonly _x25519PrivateKey: X25519PrivateKey | undefined;\n private readonly _mlkemPrivateKey: MLKEMPrivateKey | undefined;\n\n private constructor(\n scheme: EncapsulationScheme,\n x25519PrivateKey?: X25519PrivateKey,\n mlkemPrivateKey?: MLKEMPrivateKey,\n ) {\n this._scheme = scheme;\n this._x25519PrivateKey = x25519PrivateKey;\n this._mlkemPrivateKey = mlkemPrivateKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an EncapsulationPrivateKey from an X25519PrivateKey.\n */\n static fromX25519PrivateKey(privateKey: X25519PrivateKey): EncapsulationPrivateKey {\n return new EncapsulationPrivateKey(EncapsulationScheme.X25519, privateKey, undefined);\n }\n\n /**\n * Create an EncapsulationPrivateKey from raw X25519 private key bytes.\n */\n static fromX25519Data(data: Uint8Array): EncapsulationPrivateKey {\n const privateKey = X25519PrivateKey.fromDataRef(data);\n return EncapsulationPrivateKey.fromX25519PrivateKey(privateKey);\n }\n\n /**\n * Create an EncapsulationPrivateKey from an MLKEMPrivateKey.\n */\n static fromMlkem(privateKey: MLKEMPrivateKey): EncapsulationPrivateKey {\n const scheme = mlkemLevelToScheme(privateKey.level());\n return new EncapsulationPrivateKey(scheme, undefined, privateKey);\n }\n\n /**\n * Create an EncapsulationPrivateKey from raw MLKEM private key bytes.\n */\n static fromMlkemData(level: MLKEMLevel, data: Uint8Array): EncapsulationPrivateKey {\n const privateKey = MLKEMPrivateKey.fromBytes(level, data);\n return EncapsulationPrivateKey.fromMlkem(privateKey);\n }\n\n /**\n * Generate a new random X25519 encapsulation private key.\n */\n static new(): EncapsulationPrivateKey {\n return EncapsulationPrivateKey.random();\n }\n\n /**\n * Generate a new random X25519 encapsulation private key.\n */\n static random(): EncapsulationPrivateKey {\n const rng = new SecureRandomNumberGenerator();\n return EncapsulationPrivateKey.newUsing(rng);\n }\n\n /**\n * Generate a new random X25519 encapsulation private key using provided RNG.\n */\n static newUsing(rng: RandomNumberGenerator): EncapsulationPrivateKey {\n const x25519Private = X25519PrivateKey.newUsing(rng);\n return EncapsulationPrivateKey.fromX25519PrivateKey(x25519Private);\n }\n\n /**\n * Generate a new MLKEM encapsulation private key.\n */\n static newMlkem(level: MLKEMLevel = MLKEMLevel.MLKEM768): EncapsulationPrivateKey {\n const mlkemPrivate = MLKEMPrivateKey.new(level);\n return EncapsulationPrivateKey.fromMlkem(mlkemPrivate);\n }\n\n /**\n * Generate a new MLKEM encapsulation private key using provided RNG.\n */\n static newMlkemUsing(level: MLKEMLevel, rng: RandomNumberGenerator): EncapsulationPrivateKey {\n const mlkemPrivate = MLKEMPrivateKey.newUsing(level, rng);\n return EncapsulationPrivateKey.fromMlkem(mlkemPrivate);\n }\n\n /**\n * Generate a new keypair for X25519.\n */\n static keypair(): [EncapsulationPrivateKey, EncapsulationPublicKey] {\n const privateKey = EncapsulationPrivateKey.new();\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Generate a new keypair using the given RNG (X25519).\n */\n static keypairUsing(\n rng: RandomNumberGenerator,\n ): [EncapsulationPrivateKey, EncapsulationPublicKey] {\n const privateKey = EncapsulationPrivateKey.newUsing(rng);\n const publicKey = privateKey.publicKey();\n return [privateKey, publicKey];\n }\n\n /**\n * Generate a new MLKEM keypair.\n */\n static mlkemKeypair(\n level: MLKEMLevel = MLKEMLevel.MLKEM768,\n ): [EncapsulationPrivateKey, EncapsulationPublicKey] {\n const [mlkemPrivate, mlkemPublic] = MLKEMPrivateKey.keypair(level);\n const privateKey = EncapsulationPrivateKey.fromMlkem(mlkemPrivate);\n const publicKey = EncapsulationPublicKey.fromMlkem(mlkemPublic);\n return [privateKey, publicKey];\n }\n\n /**\n * Generate a new MLKEM keypair using the given RNG.\n */\n static mlkemKeypairUsing(\n level: MLKEMLevel,\n rng: RandomNumberGenerator,\n ): [EncapsulationPrivateKey, EncapsulationPublicKey] {\n const [mlkemPrivate, mlkemPublic] = MLKEMPrivateKey.keypairUsing(level, rng);\n const privateKey = EncapsulationPrivateKey.fromMlkem(mlkemPrivate);\n const publicKey = EncapsulationPublicKey.fromMlkem(mlkemPublic);\n return [privateKey, publicKey];\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the encapsulation scheme.\n */\n encapsulationScheme(): EncapsulationScheme {\n return this._scheme;\n }\n\n /**\n * Returns true if this is an X25519 private key.\n */\n isX25519(): boolean {\n return this._scheme === EncapsulationScheme.X25519;\n }\n\n /**\n * Returns true if this is an MLKEM private key.\n */\n isMlkem(): boolean {\n return isMlkemScheme(this._scheme);\n }\n\n /**\n * Returns the X25519 private key if this is an X25519 encapsulation key.\n * @throws Error if this is not an X25519 key\n */\n x25519PrivateKey(): X25519PrivateKey {\n if (this._x25519PrivateKey === undefined) {\n throw new Error(\"Not an X25519 private key\");\n }\n return this._x25519PrivateKey;\n }\n\n /**\n * Returns the MLKEM private key if this is an MLKEM encapsulation key.\n * @throws Error if this is not an MLKEM key\n */\n mlkemPrivateKey(): MLKEMPrivateKey {\n if (this._mlkemPrivateKey === undefined) {\n throw new Error(\"Not an MLKEM private key\");\n }\n return this._mlkemPrivateKey;\n }\n\n /**\n * Returns the X25519 private key if available, or null.\n */\n toX25519(): X25519PrivateKey | null {\n return this._x25519PrivateKey ?? null;\n }\n\n /**\n * Returns the MLKEM private key if available, or null.\n */\n toMlkem(): MLKEMPrivateKey | null {\n return this._mlkemPrivateKey ?? null;\n }\n\n /**\n * Returns the raw private key data.\n */\n data(): Uint8Array {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PrivateKey;\n if (pk === undefined) throw new Error(\"X25519 private key not set\");\n return pk.data();\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPrivateKey;\n if (pk === undefined) throw new Error(\"MLKEM private key not set\");\n return pk.data();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Get the public key corresponding to this private key.\n */\n publicKey(): EncapsulationPublicKey {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PrivateKey;\n if (pk === undefined) throw new Error(\"X25519 private key not set\");\n const x25519Public = pk.publicKey();\n return EncapsulationPublicKey.fromX25519PublicKey(x25519Public);\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPrivateKey;\n if (pk === undefined) throw new Error(\"MLKEM private key not set\");\n const mlkemPublic = pk.publicKey();\n return EncapsulationPublicKey.fromMlkem(mlkemPublic);\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Decapsulate a shared secret from ciphertext.\n *\n * @param ciphertext - The ciphertext from encapsulation\n * @returns The decapsulated shared secret\n * @throws CryptoError if the scheme doesn't match\n */\n decapsulateSharedSecret(ciphertext: EncapsulationCiphertext): SymmetricKey {\n // Verify scheme matches\n if (ciphertext.encapsulationScheme() !== this._scheme) {\n throw CryptoError.invalidData(\n `Scheme mismatch: expected ${String(this._scheme)}, got ${String(ciphertext.encapsulationScheme())}`,\n );\n }\n\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PrivateKey;\n if (pk === undefined) throw new Error(\"X25519 private key not set\");\n // Get the ephemeral public key from ciphertext\n const ephemeralPublic = ciphertext.x25519PublicKey();\n\n // Perform ECDH to recover shared secret\n return pk.sharedKeyWith(ephemeralPublic);\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPrivateKey;\n if (pk === undefined) throw new Error(\"MLKEM private key not set\");\n // Get the MLKEM ciphertext and decapsulate\n const mlkemCiphertext = ciphertext.mlkemCiphertext();\n return pk.decapsulate(mlkemCiphertext);\n }\n\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Compare with another EncapsulationPrivateKey.\n */\n equals(other: EncapsulationPrivateKey): boolean {\n if (this._scheme !== other._scheme) return false;\n if (this._scheme === EncapsulationScheme.X25519) {\n const thisPk = this._x25519PrivateKey;\n const otherPk = other._x25519PrivateKey;\n if (thisPk === undefined || otherPk === undefined) return false;\n return thisPk.equals(otherPk);\n } else if (isMlkemScheme(this._scheme)) {\n const thisPk = this._mlkemPrivateKey;\n const otherPk = other._mlkemPrivateKey;\n if (thisPk === undefined || otherPk === undefined) return false;\n return thisPk.equals(otherPk);\n }\n return false;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n if (this._scheme === EncapsulationScheme.X25519) {\n return `EncapsulationPrivateKey(X25519, ${bytesToHex(this.data()).substring(0, 16)}...)`;\n } else if (isMlkemScheme(this._scheme)) {\n return `EncapsulationPrivateKey(${String(this._scheme)}, ${bytesToHex(this.data()).substring(0, 16)}...)`;\n }\n return `EncapsulationPrivateKey(${String(this._scheme)})`;\n }\n\n // ============================================================================\n // ReferenceProvider Interface\n // ============================================================================\n\n /**\n * Returns a unique reference to this EncapsulationPrivateKey instance.\n *\n * The reference is derived from the SHA-256 hash of the tagged CBOR\n * representation, providing a unique, content-addressable identifier.\n */\n reference(): Reference {\n const digest = Digest.fromImage(this.taggedCborData());\n return Reference.from(digest);\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with this private key.\n */\n cborTags(): Tag[] {\n if (this._scheme === EncapsulationScheme.X25519) {\n return tagsForValues([TAG_X25519_PRIVATE_KEY.value]);\n } else if (isMlkemScheme(this._scheme)) {\n return tagsForValues([TAG_MLKEM_PRIVATE_KEY.value]);\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n */\n untaggedCbor(): Cbor {\n if (this._scheme === EncapsulationScheme.X25519) {\n const pk = this._x25519PrivateKey;\n if (pk === undefined) throw new Error(\"X25519 private key not set\");\n return toByteString(pk.data());\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPrivateKey;\n if (pk === undefined) throw new Error(\"MLKEM private key not set\");\n return pk.untaggedCbor();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an EncapsulationPrivateKey by decoding it from untagged CBOR.\n * Note: Without tags, we assume X25519 scheme.\n */\n fromUntaggedCbor(cborValue: Cbor): EncapsulationPrivateKey {\n const data = expectBytes(cborValue);\n const privateKey = X25519PrivateKey.fromDataRef(data);\n return EncapsulationPrivateKey.fromX25519PrivateKey(privateKey);\n }\n\n /**\n * Creates an EncapsulationPrivateKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): EncapsulationPrivateKey {\n const tag = tagValue(cborValue);\n\n if (tag === TAG_X25519_PRIVATE_KEY.value) {\n const content = extractTaggedContent(cborValue);\n const data = expectBytes(content);\n const privateKey = X25519PrivateKey.fromDataRef(data);\n return EncapsulationPrivateKey.fromX25519PrivateKey(privateKey);\n }\n\n if (tag === TAG_MLKEM_PRIVATE_KEY.value) {\n const mlkemPrivate = MLKEMPrivateKey.fromTaggedCbor(cborValue);\n return EncapsulationPrivateKey.fromMlkem(mlkemPrivate);\n }\n\n throw new Error(`Unknown private key tag: ${tag}`);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): EncapsulationPrivateKey {\n const dummy = EncapsulationPrivateKey.fromX25519PrivateKey(\n X25519PrivateKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): EncapsulationPrivateKey {\n const cborValue = decodeCbor(data);\n return EncapsulationPrivateKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): EncapsulationPrivateKey {\n const cborValue = decodeCbor(data);\n const dummy = EncapsulationPrivateKey.fromX25519PrivateKey(\n X25519PrivateKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n if (this._scheme === EncapsulationScheme.X25519) {\n const name = TAG_X25519_PRIVATE_KEY.name;\n if (name === undefined) throw new Error(\"TAG_X25519_PRIVATE_KEY.name is undefined\");\n return UR.new(name, this.untaggedCbor());\n } else if (isMlkemScheme(this._scheme)) {\n const pk = this._mlkemPrivateKey;\n if (pk === undefined) throw new Error(\"MLKEM private key not set\");\n return pk.ur();\n }\n throw new Error(`Unsupported scheme: ${String(this._scheme)}`);\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an EncapsulationPrivateKey from a UR.\n */\n static fromUR(ur: UR): EncapsulationPrivateKey {\n // Check for known UR types\n if (ur.urTypeStr() === TAG_X25519_PRIVATE_KEY.name) {\n const dummy = EncapsulationPrivateKey.fromX25519PrivateKey(\n X25519PrivateKey.fromData(new Uint8Array(32)),\n );\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n if (ur.urTypeStr() === TAG_MLKEM_PRIVATE_KEY.name) {\n const mlkemPrivate = MLKEMPrivateKey.fromUR(ur);\n return EncapsulationPrivateKey.fromMlkem(mlkemPrivate);\n }\n\n throw new Error(`Unknown UR type for EncapsulationPrivateKey: ${ur.urTypeStr()}`);\n }\n\n /**\n * Creates an EncapsulationPrivateKey from a UR string.\n */\n static fromURString(urString: string): EncapsulationPrivateKey {\n const ur = UR.fromURString(urString);\n return EncapsulationPrivateKey.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Encapsulation scheme enum for key encapsulation mechanisms\n *\n * This enum represents the available key encapsulation mechanisms (KEMs)\n * for establishing shared secrets between parties.\n *\n * Supported schemes:\n * - X25519: Curve25519-based Diffie-Hellman key exchange (default)\n * - MLKEM512, MLKEM768, MLKEM1024: ML-KEM at various security levels\n *\n * Ported from bc-components-rust/src/encapsulation/encapsulation_scheme.rs\n */\n\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\nimport { EncapsulationPrivateKey } from \"./encapsulation-private-key.js\";\nimport type { EncapsulationPublicKey } from \"./encapsulation-public-key.js\";\nimport { MLKEMLevel } from \"../mlkem/mlkem-level.js\";\n\n/**\n * Available key encapsulation schemes.\n */\nexport enum EncapsulationScheme {\n /**\n * X25519 Diffie-Hellman key exchange (default).\n * Based on Curve25519 as defined in RFC 7748.\n */\n X25519 = \"x25519\",\n\n /**\n * ML-KEM-512 post-quantum key encapsulation (NIST security level 1).\n */\n MLKEM512 = \"mlkem512\",\n\n /**\n * ML-KEM-768 post-quantum key encapsulation (NIST security level 3).\n */\n MLKEM768 = \"mlkem768\",\n\n /**\n * ML-KEM-1024 post-quantum key encapsulation (NIST security level 5).\n */\n MLKEM1024 = \"mlkem1024\",\n}\n\n/**\n * Returns the default encapsulation scheme (X25519).\n */\nexport function defaultEncapsulationScheme(): EncapsulationScheme {\n return EncapsulationScheme.X25519;\n}\n\n/**\n * Check if a scheme is an MLKEM scheme.\n */\nexport function isMlkemScheme(scheme: EncapsulationScheme): boolean {\n return (\n scheme === EncapsulationScheme.MLKEM512 ||\n scheme === EncapsulationScheme.MLKEM768 ||\n scheme === EncapsulationScheme.MLKEM1024\n );\n}\n\n/**\n * Convert EncapsulationScheme to MLKEMLevel.\n * @throws Error if scheme is not an MLKEM scheme\n */\nexport function schemeToMlkemLevel(scheme: EncapsulationScheme): MLKEMLevel {\n switch (scheme) {\n case EncapsulationScheme.X25519:\n throw new Error(`Not an MLKEM scheme: ${String(scheme)}`);\n case EncapsulationScheme.MLKEM512:\n return MLKEMLevel.MLKEM512;\n case EncapsulationScheme.MLKEM768:\n return MLKEMLevel.MLKEM768;\n case EncapsulationScheme.MLKEM1024:\n return MLKEMLevel.MLKEM1024;\n }\n}\n\n/**\n * Convert MLKEMLevel to EncapsulationScheme.\n */\nexport function mlkemLevelToScheme(level: MLKEMLevel): EncapsulationScheme {\n switch (level) {\n case MLKEMLevel.MLKEM512:\n return EncapsulationScheme.MLKEM512;\n case MLKEMLevel.MLKEM768:\n return EncapsulationScheme.MLKEM768;\n case MLKEMLevel.MLKEM1024:\n return EncapsulationScheme.MLKEM1024;\n }\n}\n\n/**\n * Generate a new keypair for the given encapsulation scheme.\n *\n * @param scheme - The encapsulation scheme to use (defaults to X25519)\n * @returns A tuple of [privateKey, publicKey]\n */\nexport function createEncapsulationKeypair(\n scheme: EncapsulationScheme = EncapsulationScheme.X25519,\n): [EncapsulationPrivateKey, EncapsulationPublicKey] {\n switch (scheme) {\n case EncapsulationScheme.X25519:\n return EncapsulationPrivateKey.keypair();\n case EncapsulationScheme.MLKEM512:\n return EncapsulationPrivateKey.mlkemKeypair(MLKEMLevel.MLKEM512);\n case EncapsulationScheme.MLKEM768:\n return EncapsulationPrivateKey.mlkemKeypair(MLKEMLevel.MLKEM768);\n case EncapsulationScheme.MLKEM1024:\n return EncapsulationPrivateKey.mlkemKeypair(MLKEMLevel.MLKEM1024);\n }\n}\n\n/**\n * Generate a new keypair for the given encapsulation scheme using a specific RNG.\n *\n * Note: Only X25519 supports deterministic keypair generation.\n * MLKEM schemes do not support deterministic generation (matching Rust behavior).\n *\n * @param rng - The random number generator to use\n * @param scheme - The encapsulation scheme to use (defaults to X25519)\n * @returns A tuple of [privateKey, publicKey]\n * @throws Error if the scheme doesn't support deterministic generation\n */\nexport function createEncapsulationKeypairUsing(\n rng: RandomNumberGenerator,\n scheme: EncapsulationScheme = EncapsulationScheme.X25519,\n): [EncapsulationPrivateKey, EncapsulationPublicKey] {\n switch (scheme) {\n case EncapsulationScheme.X25519:\n return EncapsulationPrivateKey.keypairUsing(rng);\n case EncapsulationScheme.MLKEM512:\n case EncapsulationScheme.MLKEM768:\n case EncapsulationScheme.MLKEM1024:\n // MLKEM doesn't support deterministic keypair generation (matching Rust behavior)\n throw new Error(\n \"Deterministic keypair generation not supported for this encapsulation scheme\",\n );\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Sealed message for anonymous authenticated encryption\n *\n * A `SealedMessage` combines key encapsulation with symmetric encryption to\n * provide anonymous authenticated encryption. The sender's identity is not\n * revealed, and only the intended recipient can decrypt the message.\n *\n * The sealing process:\n * 1. Encapsulate a new shared secret using the recipient's public key\n * 2. Use the shared secret to encrypt the plaintext with ChaCha20-Poly1305\n * 3. Return the encrypted message and the encapsulation ciphertext\n *\n * The unsealing process:\n * 1. Decapsulate the shared secret using the recipient's private key\n * 2. Use the shared secret to decrypt the ciphertext\n * 3. Return the plaintext\n *\n * Features:\n * - Anonymous sender (sender identity not revealed)\n * - Authenticated encryption\n * - Forward secrecy (each message uses different ephemeral key)\n *\n * # CBOR Serialization\n *\n * `SealedMessage` is serialized as a 2-element array with tag 40019:\n *\n * ```cddl\n * SealedMessage = #6.40019([\n * message: EncryptedMessage,\n * encapsulated_key: EncapsulationCiphertext\n * ])\n * ```\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `SealedMessage` is\n * represented with the type \"crypto-sealed\".\n *\n * Ported from bc-components-rust/src/encapsulation/sealed_message.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { SEALED_MESSAGE as TAG_SEALED_MESSAGE } from \"@bcts/tags\";\nimport { Nonce } from \"../nonce.js\";\nimport { EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { type EncapsulationScheme } from \"./encapsulation-scheme.js\";\nimport { EncapsulationCiphertext } from \"./encapsulation-ciphertext.js\";\nimport { type EncapsulationPublicKey } from \"./encapsulation-public-key.js\";\nimport { type EncapsulationPrivateKey } from \"./encapsulation-private-key.js\";\nimport { X25519PublicKey } from \"../x25519/x25519-public-key.js\";\nimport { bytesToHex } from \"../utils.js\";\n\n/**\n * A sealed message providing anonymous authenticated encryption.\n */\nexport class SealedMessage\n implements CborTaggedEncodable, CborTaggedDecodable<SealedMessage>, UREncodable\n{\n private readonly _message: EncryptedMessage;\n private readonly _encapsulatedKey: EncapsulationCiphertext;\n\n private constructor(message: EncryptedMessage, encapsulatedKey: EncapsulationCiphertext) {\n this._message = message;\n this._encapsulatedKey = encapsulatedKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a SealedMessage from its components.\n */\n static from(message: EncryptedMessage, encapsulatedKey: EncapsulationCiphertext): SealedMessage {\n return new SealedMessage(message, encapsulatedKey);\n }\n\n /**\n * Seal a message for a recipient (no additional authenticated data).\n *\n * @param plaintext - The message to encrypt\n * @param recipient - The recipient's public key\n * @returns A sealed message that only the recipient can decrypt\n */\n static new(plaintext: Uint8Array, recipient: EncapsulationPublicKey): SealedMessage {\n return SealedMessage.newWithAad(plaintext, recipient, new Uint8Array(0));\n }\n\n /**\n * Seal a message for a recipient with additional authenticated data.\n *\n * @param plaintext - The message to encrypt\n * @param recipient - The recipient's public key\n * @param aad - Additional authenticated data (not encrypted but authenticated)\n * @returns A sealed message that only the recipient can decrypt\n */\n static newWithAad(\n plaintext: Uint8Array,\n recipient: EncapsulationPublicKey,\n aad: Uint8Array,\n ): SealedMessage {\n return SealedMessage.newOpt(plaintext, recipient, aad, undefined);\n }\n\n /**\n * Seal a message with optional test nonce (for deterministic testing).\n *\n * @param plaintext - The message to encrypt\n * @param recipient - The recipient's public key\n * @param aad - Additional authenticated data\n * @param testNonce - Optional fixed nonce for testing (DO NOT use in production)\n * @returns A sealed message\n */\n static newOpt(\n plaintext: Uint8Array,\n recipient: EncapsulationPublicKey,\n aad: Uint8Array,\n testNonce?: Nonce,\n ): SealedMessage {\n // Encapsulate a new shared secret\n const [sharedSecret, ciphertext] = recipient.encapsulateNewSharedSecret();\n\n // Use the nonce or generate a random one\n const nonce = testNonce ?? Nonce.new();\n\n // Encrypt the plaintext using the shared secret\n const encryptedMessage = sharedSecret.encrypt(plaintext, aad, nonce);\n\n return new SealedMessage(encryptedMessage, ciphertext);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the encrypted message.\n */\n message(): EncryptedMessage {\n return this._message;\n }\n\n /**\n * Returns the encapsulation ciphertext (ephemeral public key for X25519).\n */\n encapsulatedKey(): EncapsulationCiphertext {\n return this._encapsulatedKey;\n }\n\n /**\n * Returns the encapsulation scheme used.\n */\n encapsulationScheme(): EncapsulationScheme {\n return this._encapsulatedKey.encapsulationScheme();\n }\n\n /**\n * Decrypt the sealed message using the recipient's private key.\n *\n * @param privateKey - The recipient's private key\n * @returns The decrypted plaintext\n * @throws Error if decryption fails\n */\n decrypt(privateKey: EncapsulationPrivateKey): Uint8Array {\n // Decapsulate the shared secret\n const sharedSecret = privateKey.decapsulateSharedSecret(this._encapsulatedKey);\n\n // Decrypt the message\n return sharedSecret.decrypt(this._message);\n }\n\n /**\n * Compare with another SealedMessage.\n */\n equals(other: SealedMessage): boolean {\n return (\n this._message.equals(other._message) && this._encapsulatedKey.equals(other._encapsulatedKey)\n );\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `SealedMessage(${this._encapsulatedKey.encapsulationScheme()}, ciphertext: ${bytesToHex(this._message.ciphertext()).substring(0, 16)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with SealedMessage.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SEALED_MESSAGE.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n * Format: [EncryptedMessage (tagged), EncapsulationCiphertext (tagged)]\n */\n untaggedCbor(): Cbor {\n const elements: Cbor[] = [this._message.taggedCbor(), this._encapsulatedKey.taggedCbor()];\n return cbor(elements);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a SealedMessage by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): SealedMessage {\n const elements = expectArray(cborValue);\n\n if (elements.length !== 2) {\n throw new Error(`SealedMessage must have 2 elements, got ${elements.length}`);\n }\n\n // Decode the encrypted message (tagged)\n const message = EncryptedMessage.fromTaggedCbor(elements[0]);\n\n // Decode the encapsulation ciphertext (tagged)\n const encapsulatedKey = EncapsulationCiphertext.fromTaggedCbor(elements[1]);\n\n return new SealedMessage(message, encapsulatedKey);\n }\n\n /**\n * Creates a SealedMessage by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): SealedMessage {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): SealedMessage {\n const dummyMessage = EncryptedMessage.new(\n new Uint8Array(0),\n new Uint8Array(0),\n Nonce.new(),\n new Uint8Array(16),\n );\n const dummyCiphertext = EncapsulationCiphertext.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n const dummy = new SealedMessage(dummyMessage, dummyCiphertext);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): SealedMessage {\n const cborValue = decodeCbor(data);\n return SealedMessage.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): SealedMessage {\n const cborValue = decodeCbor(data);\n const dummyMessage = EncryptedMessage.new(\n new Uint8Array(0),\n new Uint8Array(0),\n Nonce.new(),\n new Uint8Array(16),\n );\n const dummyCiphertext = EncapsulationCiphertext.fromX25519PublicKey(\n X25519PublicKey.fromData(new Uint8Array(32)),\n );\n const dummy = new SealedMessage(dummyMessage, dummyCiphertext);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the SealedMessage.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n const name = TAG_SEALED_MESSAGE.name;\n if (name === undefined) {\n throw new Error(\"TAG_SEALED_MESSAGE.name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a SealedMessage from a UR.\n */\n static fromUR(ur: UR): SealedMessage {\n const name = TAG_SEALED_MESSAGE.name;\n if (name === undefined) {\n throw new Error(\"TAG_SEALED_MESSAGE.name is undefined\");\n }\n ur.checkType(name);\n return SealedMessage.fromUntaggedCborData(ur.cbor().toData());\n }\n\n /**\n * Creates a SealedMessage from a UR string.\n */\n static fromURString(urString: string): SealedMessage {\n const ur = UR.fromURString(urString);\n return SealedMessage.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Hash type enum for key derivation functions\n *\n * This enum represents the supported hash algorithms for HKDF and PBKDF2.\n *\n * CDDL:\n * ```cddl\n * HashType = SHA256 / SHA512\n * SHA256 = 0\n * SHA512 = 1\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/hash_type.rs\n */\n\nimport { type Cbor, cbor, expectNumber } from \"@bcts/dcbor\";\n\n/**\n * Enum representing supported hash types for key derivation.\n */\nexport enum HashType {\n /** SHA-256 hash algorithm */\n SHA256 = 0,\n /** SHA-512 hash algorithm */\n SHA512 = 1,\n}\n\n/**\n * Convert HashType to its string representation.\n */\nexport function hashTypeToString(hashType: HashType): string {\n switch (hashType) {\n case HashType.SHA256:\n return \"SHA256\";\n case HashType.SHA512:\n return \"SHA512\";\n default:\n throw new Error(`Unknown HashType: ${String(hashType)}`);\n }\n}\n\n/**\n * Convert HashType to CBOR.\n */\nexport function hashTypeToCbor(hashType: HashType): Cbor {\n return cbor(hashType);\n}\n\n/**\n * Parse HashType from CBOR.\n */\nexport function hashTypeFromCbor(cborValue: Cbor): HashType {\n const value = expectNumber(cborValue);\n switch (value) {\n case 0:\n return HashType.SHA256;\n case 1:\n return HashType.SHA512;\n default:\n throw new Error(`Invalid HashType: ${value}`);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Key derivation method enum\n *\n * This enum represents the supported key derivation methods for encrypting keys.\n *\n * CDDL:\n * ```cddl\n * KeyDerivationMethod = HKDF / PBKDF2 / Scrypt / Argon2id / SSHAgent\n * HKDF = 0\n * PBKDF2 = 1\n * Scrypt = 2\n * Argon2id = 3\n * SSHAgent = 4\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/key_derivation_method.rs\n */\n\nimport { type Cbor, expectNumber } from \"@bcts/dcbor\";\n\n/**\n * Enum representing supported key derivation methods.\n */\nexport enum KeyDerivationMethod {\n /** HKDF (HMAC-based Key Derivation Function) - RFC 5869 */\n HKDF = 0,\n /** PBKDF2 (Password-Based Key Derivation Function 2) - RFC 8018 */\n PBKDF2 = 1,\n /** Scrypt - RFC 7914 */\n Scrypt = 2,\n /** Argon2id - RFC 9106 (default, most secure for passwords) */\n Argon2id = 3,\n /** SSH Agent - Uses SSH agent for key derivation */\n SSHAgent = 4,\n}\n\n/**\n * Returns the default key derivation method (Argon2id).\n */\nexport function defaultKeyDerivationMethod(): KeyDerivationMethod {\n return KeyDerivationMethod.Argon2id;\n}\n\n/**\n * Returns the zero-based index of the key derivation method.\n */\nexport function keyDerivationMethodIndex(method: KeyDerivationMethod): number {\n return method;\n}\n\n/**\n * Attempts to create a KeyDerivationMethod from a zero-based index.\n */\nexport function keyDerivationMethodFromIndex(index: number): KeyDerivationMethod | undefined {\n switch (index) {\n case 0:\n return KeyDerivationMethod.HKDF;\n case 1:\n return KeyDerivationMethod.PBKDF2;\n case 2:\n return KeyDerivationMethod.Scrypt;\n case 3:\n return KeyDerivationMethod.Argon2id;\n case 4:\n return KeyDerivationMethod.SSHAgent;\n default:\n return undefined;\n }\n}\n\n/**\n * Convert KeyDerivationMethod to its string representation.\n */\nexport function keyDerivationMethodToString(method: KeyDerivationMethod): string {\n switch (method) {\n case KeyDerivationMethod.HKDF:\n return \"HKDF\";\n case KeyDerivationMethod.PBKDF2:\n return \"PBKDF2\";\n case KeyDerivationMethod.Scrypt:\n return \"Scrypt\";\n case KeyDerivationMethod.Argon2id:\n return \"Argon2id\";\n case KeyDerivationMethod.SSHAgent:\n return \"SSHAgent\";\n default:\n throw new Error(`Unknown KeyDerivationMethod: ${String(method)}`);\n }\n}\n\n/**\n * Parse KeyDerivationMethod from CBOR.\n */\nexport function keyDerivationMethodFromCbor(cborValue: Cbor): KeyDerivationMethod {\n const value = expectNumber(cborValue);\n const method = keyDerivationMethodFromIndex(Number(value));\n if (method === undefined) {\n throw new Error(`Invalid KeyDerivationMethod index: ${value}`);\n }\n return method;\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * HKDF (HMAC-based Key Derivation Function) parameters\n *\n * HKDF is a key derivation function based on HMAC, defined in RFC 5869.\n * It is NOT suitable for password-based key derivation (use PBKDF2, Scrypt,\n * or Argon2id instead).\n *\n * CDDL:\n * ```cddl\n * HKDFParams = [0, Salt, HashType]\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/hkdf_params.rs\n */\n\nimport { type Cbor, cbor, expectArray, expectNumber, expectBytes } from \"@bcts/dcbor\";\nimport { hkdfHmacSha256, hkdfHmacSha512 } from \"@bcts/crypto\";\n\nimport { Salt } from \"../salt.js\";\nimport { Nonce } from \"../nonce.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { type EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { HashType, hashTypeToCbor, hashTypeFromCbor, hashTypeToString } from \"./hash-type.js\";\nimport { KeyDerivationMethod } from \"./key-derivation-method.js\";\nimport type { KeyDerivation } from \"./key-derivation.js\";\n\n/** Default salt length for key derivation */\nexport const SALT_LEN = 16;\n\n/**\n * HKDF parameters for key derivation.\n *\n * HKDF is suitable for deriving keys from high-entropy inputs (like other keys),\n * but NOT for password-based key derivation.\n */\nexport class HKDFParams implements KeyDerivation {\n static readonly INDEX = KeyDerivationMethod.HKDF;\n\n private readonly _salt: Salt;\n private readonly _hashType: HashType;\n\n private constructor(salt: Salt, hashType: HashType) {\n this._salt = salt;\n this._hashType = hashType;\n }\n\n /**\n * Create new HKDF parameters with default settings.\n * Uses a random 16-byte salt and SHA-256.\n */\n static new(): HKDFParams {\n return HKDFParams.newOpt(Salt.newWithLen(SALT_LEN), HashType.SHA256);\n }\n\n /**\n * Create HKDF parameters with custom settings.\n */\n static newOpt(salt: Salt, hashType: HashType): HKDFParams {\n return new HKDFParams(salt, hashType);\n }\n\n /** Returns the salt. */\n salt(): Salt {\n return this._salt;\n }\n\n /** Returns the hash type. */\n hashType(): HashType {\n return this._hashType;\n }\n\n /** Returns the method index for CBOR encoding. */\n index(): number {\n return HKDFParams.INDEX;\n }\n\n /**\n * Derive a key from the secret and encrypt the content key.\n */\n lock(contentKey: SymmetricKey, secret: Uint8Array): EncryptedMessage {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Encode the method parameters as AAD\n const encodedMethod = this.toCbor().toData();\n\n // Encrypt the content key using the derived key\n return derivedKey.encrypt(contentKey.data(), encodedMethod, Nonce.new());\n }\n\n /**\n * Derive a key from the secret and decrypt the content key.\n */\n unlock(encryptedMessage: EncryptedMessage, secret: Uint8Array): SymmetricKey {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Decrypt to get the content key\n const contentKeyData = derivedKey.decrypt(encryptedMessage);\n return SymmetricKey.fromData(contentKeyData);\n }\n\n private _deriveKey(secret: Uint8Array): Uint8Array {\n switch (this._hashType) {\n case HashType.SHA256:\n return hkdfHmacSha256(secret, this._salt.asBytes(), 32);\n case HashType.SHA512:\n return hkdfHmacSha512(secret, this._salt.asBytes(), 32);\n default:\n throw new Error(`Unknown hash type: ${String(this._hashType)}`);\n }\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `HKDF(${hashTypeToString(this._hashType)})`;\n }\n\n /**\n * Check equality with another HKDFParams.\n */\n equals(other: HKDFParams): boolean {\n return this._salt.equals(other._salt) && this._hashType === other._hashType;\n }\n\n // ============================================================================\n // CBOR Serialization\n // ============================================================================\n\n /**\n * Convert to CBOR.\n * Format: [0, Salt, HashType]\n */\n toCbor(): Cbor {\n return cbor([\n cbor(HKDFParams.INDEX),\n this._salt.untaggedCbor(),\n hashTypeToCbor(this._hashType),\n ]);\n }\n\n /**\n * Convert to CBOR binary data.\n */\n toCborData(): Uint8Array {\n return this.toCbor().toData();\n }\n\n /**\n * Parse from CBOR.\n */\n static fromCbor(cborValue: Cbor): HKDFParams {\n const array = expectArray(cborValue);\n\n if (array.length !== 3) {\n throw new Error(`Invalid HKDFParams: expected 3 elements, got ${array.length}`);\n }\n\n const index = expectNumber(array[0]);\n if (index !== HKDFParams.INDEX) {\n throw new Error(`Invalid HKDFParams index: expected ${HKDFParams.INDEX}, got ${index}`);\n }\n\n const saltData = expectBytes(array[1]);\n const salt = Salt.fromData(saltData);\n const hashType = hashTypeFromCbor(array[2]);\n\n return new HKDFParams(salt, hashType);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * PBKDF2 (Password-Based Key Derivation Function 2) parameters\n *\n * PBKDF2 is a key derivation function defined in RFC 8018 (PKCS #5 v2.1).\n * It is suitable for password-based key derivation.\n *\n * CDDL:\n * ```cddl\n * PBKDF2Params = [1, Salt, iterations: uint, HashType]\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/pbkdf2_params.rs\n */\n\nimport { type Cbor, cbor, expectArray, expectNumber, expectBytes } from \"@bcts/dcbor\";\nimport { pbkdf2HmacSha256, pbkdf2HmacSha512 } from \"@bcts/crypto\";\n\nimport { Salt } from \"../salt.js\";\nimport { Nonce } from \"../nonce.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { type EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { HashType, hashTypeToCbor, hashTypeFromCbor, hashTypeToString } from \"./hash-type.js\";\nimport { KeyDerivationMethod } from \"./key-derivation-method.js\";\nimport { SALT_LEN } from \"./hkdf-params.js\";\nimport type { KeyDerivation } from \"./key-derivation.js\";\n\n/** Default number of iterations for PBKDF2 */\nexport const DEFAULT_PBKDF2_ITERATIONS = 100_000;\n\n/**\n * PBKDF2 parameters for password-based key derivation.\n */\nexport class PBKDF2Params implements KeyDerivation {\n static readonly INDEX = KeyDerivationMethod.PBKDF2;\n\n private readonly _salt: Salt;\n private readonly _iterations: number;\n private readonly _hashType: HashType;\n\n private constructor(salt: Salt, iterations: number, hashType: HashType) {\n this._salt = salt;\n this._iterations = iterations;\n this._hashType = hashType;\n }\n\n /**\n * Create new PBKDF2 parameters with default settings.\n * Uses a random 16-byte salt, 100,000 iterations, and SHA-256.\n */\n static new(): PBKDF2Params {\n return PBKDF2Params.newOpt(\n Salt.newWithLen(SALT_LEN),\n DEFAULT_PBKDF2_ITERATIONS,\n HashType.SHA256,\n );\n }\n\n /**\n * Create PBKDF2 parameters with custom settings.\n */\n static newOpt(salt: Salt, iterations: number, hashType: HashType): PBKDF2Params {\n return new PBKDF2Params(salt, iterations, hashType);\n }\n\n /** Returns the salt. */\n salt(): Salt {\n return this._salt;\n }\n\n /** Returns the number of iterations. */\n iterations(): number {\n return this._iterations;\n }\n\n /** Returns the hash type. */\n hashType(): HashType {\n return this._hashType;\n }\n\n /** Returns the method index for CBOR encoding. */\n index(): number {\n return PBKDF2Params.INDEX;\n }\n\n /**\n * Derive a key from the secret and encrypt the content key.\n */\n lock(contentKey: SymmetricKey, secret: Uint8Array): EncryptedMessage {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Encode the method parameters as AAD\n const encodedMethod = this.toCbor().toData();\n\n // Encrypt the content key using the derived key\n return derivedKey.encrypt(contentKey.data(), encodedMethod, Nonce.new());\n }\n\n /**\n * Derive a key from the secret and decrypt the content key.\n */\n unlock(encryptedMessage: EncryptedMessage, secret: Uint8Array): SymmetricKey {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Decrypt to get the content key\n const contentKeyData = derivedKey.decrypt(encryptedMessage);\n return SymmetricKey.fromData(contentKeyData);\n }\n\n private _deriveKey(secret: Uint8Array): Uint8Array {\n switch (this._hashType) {\n case HashType.SHA256:\n return pbkdf2HmacSha256(secret, this._salt.asBytes(), this._iterations, 32);\n case HashType.SHA512:\n return pbkdf2HmacSha512(secret, this._salt.asBytes(), this._iterations, 32);\n default:\n throw new Error(`Unknown hash type: ${String(this._hashType)}`);\n }\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `PBKDF2(${hashTypeToString(this._hashType)})`;\n }\n\n /**\n * Check equality with another PBKDF2Params.\n */\n equals(other: PBKDF2Params): boolean {\n return (\n this._salt.equals(other._salt) &&\n this._iterations === other._iterations &&\n this._hashType === other._hashType\n );\n }\n\n // ============================================================================\n // CBOR Serialization\n // ============================================================================\n\n /**\n * Convert to CBOR.\n * Format: [1, Salt, iterations, HashType]\n */\n toCbor(): Cbor {\n return cbor([\n cbor(PBKDF2Params.INDEX),\n this._salt.untaggedCbor(),\n cbor(this._iterations),\n hashTypeToCbor(this._hashType),\n ]);\n }\n\n /**\n * Convert to CBOR binary data.\n */\n toCborData(): Uint8Array {\n return this.toCbor().toData();\n }\n\n /**\n * Parse from CBOR.\n */\n static fromCbor(cborValue: Cbor): PBKDF2Params {\n const array = expectArray(cborValue);\n\n if (array.length !== 4) {\n throw new Error(`Invalid PBKDF2Params: expected 4 elements, got ${array.length}`);\n }\n\n const index = expectNumber(array[0]);\n if (index !== PBKDF2Params.INDEX) {\n throw new Error(`Invalid PBKDF2Params index: expected ${PBKDF2Params.INDEX}, got ${index}`);\n }\n\n const saltData = expectBytes(array[1]);\n const salt = Salt.fromData(saltData);\n const iterations = Number(expectNumber(array[2]));\n const hashType = hashTypeFromCbor(array[3]);\n\n return new PBKDF2Params(salt, iterations, hashType);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Scrypt parameters for password-based key derivation\n *\n * Scrypt is a memory-hard key derivation function defined in RFC 7914.\n * It is suitable for password-based key derivation and is more resistant\n * to hardware brute-force attacks than PBKDF2.\n *\n * CDDL:\n * ```cddl\n * ScryptParams = [2, Salt, log_n: uint, r: uint, p: uint]\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/scrypt_params.rs\n */\n\nimport { type Cbor, cbor, expectArray, expectNumber, expectBytes } from \"@bcts/dcbor\";\nimport { scryptOpt } from \"@bcts/crypto\";\n\nimport { Salt } from \"../salt.js\";\nimport { Nonce } from \"../nonce.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { type EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { KeyDerivationMethod } from \"./key-derivation-method.js\";\nimport { SALT_LEN } from \"./hkdf-params.js\";\nimport type { KeyDerivation } from \"./key-derivation.js\";\n\n/** Default log_n parameter (2^15 = 32768 iterations) */\nexport const DEFAULT_SCRYPT_LOG_N = 15;\n/** Default r parameter (block size) */\nexport const DEFAULT_SCRYPT_R = 8;\n/** Default p parameter (parallelism) */\nexport const DEFAULT_SCRYPT_P = 1;\n\n/**\n * Scrypt parameters for password-based key derivation.\n *\n * Parameters:\n * - log_n: CPU/memory cost parameter (N = 2^log_n)\n * - r: Block size parameter\n * - p: Parallelization parameter\n */\nexport class ScryptParams implements KeyDerivation {\n static readonly INDEX = KeyDerivationMethod.Scrypt;\n\n private readonly _salt: Salt;\n private readonly _logN: number;\n private readonly _r: number;\n private readonly _p: number;\n\n private constructor(salt: Salt, logN: number, r: number, p: number) {\n this._salt = salt;\n this._logN = logN;\n this._r = r;\n this._p = p;\n }\n\n /**\n * Create new Scrypt parameters with default settings.\n * Uses a random 16-byte salt, log_n=15, r=8, p=1.\n */\n static new(): ScryptParams {\n return ScryptParams.newOpt(\n Salt.newWithLen(SALT_LEN),\n DEFAULT_SCRYPT_LOG_N,\n DEFAULT_SCRYPT_R,\n DEFAULT_SCRYPT_P,\n );\n }\n\n /**\n * Create Scrypt parameters with custom settings.\n */\n static newOpt(salt: Salt, logN: number, r: number, p: number): ScryptParams {\n return new ScryptParams(salt, logN, r, p);\n }\n\n /** Returns the salt. */\n salt(): Salt {\n return this._salt;\n }\n\n /** Returns the log_n parameter. */\n logN(): number {\n return this._logN;\n }\n\n /** Returns the r parameter (block size). */\n r(): number {\n return this._r;\n }\n\n /** Returns the p parameter (parallelism). */\n p(): number {\n return this._p;\n }\n\n /** Returns the method index for CBOR encoding. */\n index(): number {\n return ScryptParams.INDEX;\n }\n\n /**\n * Derive a key from the secret and encrypt the content key.\n */\n lock(contentKey: SymmetricKey, secret: Uint8Array): EncryptedMessage {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Encode the method parameters as AAD\n const encodedMethod = this.toCbor().toData();\n\n // Encrypt the content key using the derived key\n return derivedKey.encrypt(contentKey.data(), encodedMethod, Nonce.new());\n }\n\n /**\n * Derive a key from the secret and decrypt the content key.\n */\n unlock(encryptedMessage: EncryptedMessage, secret: Uint8Array): SymmetricKey {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Decrypt to get the content key\n const contentKeyData = derivedKey.decrypt(encryptedMessage);\n return SymmetricKey.fromData(contentKeyData);\n }\n\n private _deriveKey(secret: Uint8Array): Uint8Array {\n return scryptOpt(secret, this._salt.asBytes(), 32, this._logN, this._r, this._p);\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return \"Scrypt\";\n }\n\n /**\n * Check equality with another ScryptParams.\n */\n equals(other: ScryptParams): boolean {\n return (\n this._salt.equals(other._salt) &&\n this._logN === other._logN &&\n this._r === other._r &&\n this._p === other._p\n );\n }\n\n // ============================================================================\n // CBOR Serialization\n // ============================================================================\n\n /**\n * Convert to CBOR.\n * Format: [2, Salt, log_n, r, p]\n */\n toCbor(): Cbor {\n return cbor([\n cbor(ScryptParams.INDEX),\n this._salt.untaggedCbor(),\n cbor(this._logN),\n cbor(this._r),\n cbor(this._p),\n ]);\n }\n\n /**\n * Convert to CBOR binary data.\n */\n toCborData(): Uint8Array {\n return this.toCbor().toData();\n }\n\n /**\n * Parse from CBOR.\n */\n static fromCbor(cborValue: Cbor): ScryptParams {\n const array = expectArray(cborValue);\n\n if (array.length !== 5) {\n throw new Error(`Invalid ScryptParams: expected 5 elements, got ${array.length}`);\n }\n\n const index = expectNumber(array[0]);\n if (index !== ScryptParams.INDEX) {\n throw new Error(`Invalid ScryptParams index: expected ${ScryptParams.INDEX}, got ${index}`);\n }\n\n const saltData = expectBytes(array[1]);\n const salt = Salt.fromData(saltData);\n const logN = Number(expectNumber(array[2]));\n const r = Number(expectNumber(array[3]));\n const p = Number(expectNumber(array[4]));\n\n return new ScryptParams(salt, logN, r, p);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Argon2id parameters for password-based key derivation\n *\n * Argon2id is a memory-hard key derivation function defined in RFC 9106.\n * It combines Argon2i (resistant to side-channel attacks) and Argon2d\n * (resistant to GPU cracking attacks). It is the recommended choice for\n * password-based key derivation.\n *\n * CDDL:\n * ```cddl\n * Argon2idParams = [3, Salt]\n * ```\n *\n * Note: Argon2id uses sensible defaults for memory, iterations, and parallelism.\n * Only the salt is configurable in the CBOR encoding for simplicity.\n *\n * Ported from bc-components-rust/src/encrypted_key/argon2id_params.rs\n */\n\nimport { type Cbor, cbor, expectArray, expectNumber, expectBytes } from \"@bcts/dcbor\";\nimport { argon2id } from \"@bcts/crypto\";\n\nimport { Salt } from \"../salt.js\";\nimport { Nonce } from \"../nonce.js\";\nimport { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { type EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { KeyDerivationMethod } from \"./key-derivation-method.js\";\nimport { SALT_LEN } from \"./hkdf-params.js\";\nimport type { KeyDerivation } from \"./key-derivation.js\";\n\n/**\n * Argon2id parameters for password-based key derivation.\n *\n * This is the recommended method for password-based key derivation as it\n * provides the best protection against both GPU cracking and side-channel\n * attacks.\n */\nexport class Argon2idParams implements KeyDerivation {\n static readonly INDEX = KeyDerivationMethod.Argon2id;\n\n private readonly _salt: Salt;\n\n private constructor(salt: Salt) {\n this._salt = salt;\n }\n\n /**\n * Create new Argon2id parameters with default settings.\n * Uses a random 16-byte salt.\n */\n static new(): Argon2idParams {\n return Argon2idParams.newOpt(Salt.newWithLen(SALT_LEN));\n }\n\n /**\n * Create Argon2id parameters with a custom salt.\n */\n static newOpt(salt: Salt): Argon2idParams {\n return new Argon2idParams(salt);\n }\n\n /** Returns the salt. */\n salt(): Salt {\n return this._salt;\n }\n\n /** Returns the method index for CBOR encoding. */\n index(): number {\n return Argon2idParams.INDEX;\n }\n\n /**\n * Derive a key from the secret and encrypt the content key.\n */\n lock(contentKey: SymmetricKey, secret: Uint8Array): EncryptedMessage {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Encode the method parameters as AAD\n const encodedMethod = this.toCbor().toData();\n\n // Encrypt the content key using the derived key\n return derivedKey.encrypt(contentKey.data(), encodedMethod, Nonce.new());\n }\n\n /**\n * Derive a key from the secret and decrypt the content key.\n */\n unlock(encryptedMessage: EncryptedMessage, secret: Uint8Array): SymmetricKey {\n const derivedKeyData = this._deriveKey(secret);\n const derivedKey = SymmetricKey.fromData(derivedKeyData);\n\n // Decrypt to get the content key\n const contentKeyData = derivedKey.decrypt(encryptedMessage);\n return SymmetricKey.fromData(contentKeyData);\n }\n\n private _deriveKey(secret: Uint8Array): Uint8Array {\n return argon2id(secret, this._salt.asBytes(), 32);\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return \"Argon2id\";\n }\n\n /**\n * Check equality with another Argon2idParams.\n */\n equals(other: Argon2idParams): boolean {\n return this._salt.equals(other._salt);\n }\n\n // ============================================================================\n // CBOR Serialization\n // ============================================================================\n\n /**\n * Convert to CBOR.\n * Format: [3, Salt]\n */\n toCbor(): Cbor {\n return cbor([cbor(Argon2idParams.INDEX), this._salt.untaggedCbor()]);\n }\n\n /**\n * Convert to CBOR binary data.\n */\n toCborData(): Uint8Array {\n return this.toCbor().toData();\n }\n\n /**\n * Parse from CBOR.\n */\n static fromCbor(cborValue: Cbor): Argon2idParams {\n const array = expectArray(cborValue);\n\n if (array.length !== 2) {\n throw new Error(`Invalid Argon2idParams: expected 2 elements, got ${array.length}`);\n }\n\n const index = expectNumber(array[0]);\n if (index !== Argon2idParams.INDEX) {\n throw new Error(\n `Invalid Argon2idParams index: expected ${Argon2idParams.INDEX}, got ${index}`,\n );\n }\n\n const saltData = expectBytes(array[1]);\n const salt = Salt.fromData(saltData);\n\n return new Argon2idParams(salt);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * SSH Agent key derivation parameters\n *\n * SSH Agent uses an SSH agent daemon for key derivation. The agent signs\n * a challenge derived from the salt to produce the encryption key.\n *\n * CDDL:\n * ```cddl\n * SSHAgentParams = [4, Salt, id: tstr]\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/ssh_agent_params.rs\n */\n\nimport { type Cbor, cbor, expectArray, expectNumber, expectBytes, expectText } from \"@bcts/dcbor\";\n\nimport { Salt } from \"../salt.js\";\nimport type { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport type { EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { KeyDerivationMethod } from \"./key-derivation-method.js\";\nimport type { KeyDerivation } from \"./key-derivation.js\";\nimport { CryptoError } from \"../error.js\";\n\n/** Default salt length for SSH agent key derivation */\nexport const SALT_LEN = 16;\n\n/**\n * SSH Agent parameters for key derivation.\n *\n * This method uses an SSH agent daemon to derive encryption keys.\n * The agent signs a challenge derived from the salt using the specified\n * SSH key identity, and the signature is used to derive the encryption key.\n *\n * **Note:** SSH agent communication requires platform-specific support and\n * may not be available in all JavaScript environments. The lock/unlock\n * methods will throw an error if SSH agent support is not available.\n */\nexport class SSHAgentParams implements KeyDerivation {\n static readonly INDEX = KeyDerivationMethod.SSHAgent;\n\n private readonly _salt: Salt;\n private readonly _id: string;\n\n private constructor(salt: Salt, id: string) {\n this._salt = salt;\n this._id = id;\n }\n\n /**\n * Create new SSH agent parameters with default salt and specified key ID.\n *\n * @param id - The SSH key identity (usually the key comment or public key fingerprint)\n */\n static new(id: string): SSHAgentParams {\n return SSHAgentParams.newOpt(Salt.newWithLen(SALT_LEN), id);\n }\n\n /**\n * Create SSH agent parameters with custom salt and key ID.\n *\n * @param salt - The salt for key derivation\n * @param id - The SSH key identity\n */\n static newOpt(salt: Salt, id: string): SSHAgentParams {\n return new SSHAgentParams(salt, id);\n }\n\n /** Returns the salt. */\n salt(): Salt {\n return this._salt;\n }\n\n /** Returns the SSH key identity. */\n id(): string {\n return this._id;\n }\n\n /** Returns the method index for CBOR encoding. */\n index(): number {\n return SSHAgentParams.INDEX;\n }\n\n /**\n * Derive a key using SSH agent and encrypt the content key.\n *\n * **Note:** This method requires SSH agent support which is not yet\n * implemented in this TypeScript port. Use an alternative key derivation\n * method or implement SSH agent communication for your environment.\n *\n * @throws CryptoError - SSH agent support is not available\n */\n lock(_contentKey: SymmetricKey, _secret: Uint8Array): EncryptedMessage {\n throw CryptoError.sshAgent(\n \"SSH agent key derivation is not yet implemented in this TypeScript port. \" +\n \"Use HKDF, PBKDF2, Scrypt, or Argon2id instead.\",\n );\n }\n\n /**\n * Derive a key using SSH agent and decrypt the content key.\n *\n * **Note:** This method requires SSH agent support which is not yet\n * implemented in this TypeScript port. Use an alternative key derivation\n * method or implement SSH agent communication for your environment.\n *\n * @throws CryptoError - SSH agent support is not available\n */\n unlock(_encryptedMessage: EncryptedMessage, _secret: Uint8Array): SymmetricKey {\n throw CryptoError.sshAgent(\n \"SSH agent key derivation is not yet implemented in this TypeScript port. \" +\n \"Use HKDF, PBKDF2, Scrypt, or Argon2id instead.\",\n );\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `SSHAgent(id: \"${this._id}\")`;\n }\n\n /**\n * Check equality with another SSHAgentParams.\n */\n equals(other: SSHAgentParams): boolean {\n return this._salt.equals(other._salt) && this._id === other._id;\n }\n\n // ============================================================================\n // CBOR Serialization\n // ============================================================================\n\n /**\n * Convert to CBOR.\n * Format: [4, Salt, id: tstr]\n */\n toCbor(): Cbor {\n return cbor([cbor(SSHAgentParams.INDEX), this._salt.untaggedCbor(), cbor(this._id)]);\n }\n\n /**\n * Convert to CBOR binary data.\n */\n toCborData(): Uint8Array {\n return this.toCbor().toData();\n }\n\n /**\n * Parse from CBOR.\n */\n static fromCbor(cborValue: Cbor): SSHAgentParams {\n const array = expectArray(cborValue);\n\n if (array.length !== 3) {\n throw new Error(`Invalid SSHAgentParams: expected 3 elements, got ${array.length}`);\n }\n\n const index = expectNumber(array[0]);\n if (index !== SSHAgentParams.INDEX) {\n throw new Error(\n `Invalid SSHAgentParams index: expected ${SSHAgentParams.INDEX}, got ${index}`,\n );\n }\n\n const saltData = expectBytes(array[1]);\n const salt = Salt.fromData(saltData);\n const id = expectText(array[2]);\n\n return new SSHAgentParams(salt, id);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Key derivation parameters union type\n *\n * This type represents the derivation parameters for all supported methods.\n * It provides a unified interface for locking and unlocking keys regardless\n * of the underlying derivation method.\n *\n * Ported from bc-components-rust/src/encrypted_key/key_derivation_params.rs\n */\n\nimport { type Cbor, expectArray, expectNumber } from \"@bcts/dcbor\";\n\nimport type { SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport type { EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { KeyDerivationMethod, keyDerivationMethodFromIndex } from \"./key-derivation-method.js\";\nimport { HKDFParams } from \"./hkdf-params.js\";\nimport { PBKDF2Params } from \"./pbkdf2-params.js\";\nimport { ScryptParams } from \"./scrypt-params.js\";\nimport { Argon2idParams } from \"./argon2id-params.js\";\nimport { SSHAgentParams } from \"./ssh-agent-params.js\";\n\n/**\n * Union type representing key derivation parameters.\n *\n * Use the `method()` function to get the derivation method, and\n * `lock()`/`unlock()` for key operations.\n */\nexport type KeyDerivationParams =\n | { type: \"hkdf\"; params: HKDFParams }\n | { type: \"pbkdf2\"; params: PBKDF2Params }\n | { type: \"scrypt\"; params: ScryptParams }\n | { type: \"argon2id\"; params: Argon2idParams }\n | { type: \"sshagent\"; params: SSHAgentParams };\n\n/**\n * Create HKDF derivation parameters.\n */\nexport function hkdfParams(params?: HKDFParams): KeyDerivationParams {\n return { type: \"hkdf\", params: params ?? HKDFParams.new() };\n}\n\n/**\n * Create PBKDF2 derivation parameters.\n */\nexport function pbkdf2Params(params?: PBKDF2Params): KeyDerivationParams {\n return { type: \"pbkdf2\", params: params ?? PBKDF2Params.new() };\n}\n\n/**\n * Create Scrypt derivation parameters.\n */\nexport function scryptParams(params?: ScryptParams): KeyDerivationParams {\n return { type: \"scrypt\", params: params ?? ScryptParams.new() };\n}\n\n/**\n * Create Argon2id derivation parameters.\n */\nexport function argon2idParams(params?: Argon2idParams): KeyDerivationParams {\n return { type: \"argon2id\", params: params ?? Argon2idParams.new() };\n}\n\n/**\n * Create SSH agent derivation parameters.\n *\n * @param idOrParams - Either an SSH key identity string or SSHAgentParams instance\n */\nexport function sshAgentParams(idOrParams: string | SSHAgentParams): KeyDerivationParams {\n if (typeof idOrParams === \"string\") {\n return { type: \"sshagent\", params: SSHAgentParams.new(idOrParams) };\n }\n return { type: \"sshagent\", params: idOrParams };\n}\n\n/**\n * Create default key derivation parameters (Argon2id).\n */\nexport function defaultKeyDerivationParams(): KeyDerivationParams {\n return argon2idParams();\n}\n\n/**\n * Get the key derivation method for the given parameters.\n */\nexport function keyDerivationParamsMethod(kdp: KeyDerivationParams): KeyDerivationMethod {\n switch (kdp.type) {\n case \"hkdf\":\n return KeyDerivationMethod.HKDF;\n case \"pbkdf2\":\n return KeyDerivationMethod.PBKDF2;\n case \"scrypt\":\n return KeyDerivationMethod.Scrypt;\n case \"argon2id\":\n return KeyDerivationMethod.Argon2id;\n case \"sshagent\":\n return KeyDerivationMethod.SSHAgent;\n }\n}\n\n/**\n * Check if the parameters use a password-based method.\n * Password-based methods (PBKDF2, Scrypt, Argon2id) are designed for\n * low-entropy secrets like passwords.\n */\nexport function isPasswordBased(kdp: KeyDerivationParams): boolean {\n return kdp.type === \"pbkdf2\" || kdp.type === \"scrypt\" || kdp.type === \"argon2id\";\n}\n\n/**\n * Check if the parameters use SSH Agent for key derivation.\n *\n * Note: SSH Agent key derivation is not yet functional in TypeScript.\n * This function is useful for detecting envelopes locked by other\n * implementations (e.g., Rust).\n */\nexport function isSshAgent(kdp: KeyDerivationParams): boolean {\n return kdp.type === \"sshagent\";\n}\n\n/**\n * Lock (encrypt) a content key using the derived key.\n */\nexport function lockWithParams(\n kdp: KeyDerivationParams,\n contentKey: SymmetricKey,\n secret: Uint8Array,\n): EncryptedMessage {\n switch (kdp.type) {\n case \"hkdf\":\n return kdp.params.lock(contentKey, secret);\n case \"pbkdf2\":\n return kdp.params.lock(contentKey, secret);\n case \"scrypt\":\n return kdp.params.lock(contentKey, secret);\n case \"argon2id\":\n return kdp.params.lock(contentKey, secret);\n case \"sshagent\":\n return kdp.params.lock(contentKey, secret);\n }\n}\n\n/**\n * Convert KeyDerivationParams to CBOR.\n */\nexport function keyDerivationParamsToCbor(kdp: KeyDerivationParams): Cbor {\n switch (kdp.type) {\n case \"hkdf\":\n return kdp.params.toCbor();\n case \"pbkdf2\":\n return kdp.params.toCbor();\n case \"scrypt\":\n return kdp.params.toCbor();\n case \"argon2id\":\n return kdp.params.toCbor();\n case \"sshagent\":\n return kdp.params.toCbor();\n }\n}\n\n/**\n * Convert KeyDerivationParams to CBOR binary data.\n */\nexport function keyDerivationParamsToCborData(kdp: KeyDerivationParams): Uint8Array {\n return keyDerivationParamsToCbor(kdp).toData();\n}\n\n/**\n * Get string representation of KeyDerivationParams.\n */\nexport function keyDerivationParamsToString(kdp: KeyDerivationParams): string {\n switch (kdp.type) {\n case \"hkdf\":\n return kdp.params.toString();\n case \"pbkdf2\":\n return kdp.params.toString();\n case \"scrypt\":\n return kdp.params.toString();\n case \"argon2id\":\n return kdp.params.toString();\n case \"sshagent\":\n return kdp.params.toString();\n }\n}\n\n/**\n * Parse KeyDerivationParams from CBOR.\n */\nexport function keyDerivationParamsFromCbor(cborValue: Cbor): KeyDerivationParams {\n const array = expectArray(cborValue);\n if (array.length === 0) {\n throw new Error(\"Invalid KeyDerivationParams: empty array\");\n }\n\n const index = expectNumber(array[0]);\n const method = keyDerivationMethodFromIndex(Number(index));\n\n if (method === undefined) {\n throw new Error(`Invalid KeyDerivationMethod index: ${index}`);\n }\n\n switch (method) {\n case KeyDerivationMethod.HKDF:\n return { type: \"hkdf\", params: HKDFParams.fromCbor(cborValue) };\n case KeyDerivationMethod.PBKDF2:\n return { type: \"pbkdf2\", params: PBKDF2Params.fromCbor(cborValue) };\n case KeyDerivationMethod.Scrypt:\n return { type: \"scrypt\", params: ScryptParams.fromCbor(cborValue) };\n case KeyDerivationMethod.Argon2id:\n return { type: \"argon2id\", params: Argon2idParams.fromCbor(cborValue) };\n case KeyDerivationMethod.SSHAgent:\n return { type: \"sshagent\", params: SSHAgentParams.fromCbor(cborValue) };\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * Encrypted key for secure symmetric key storage\n *\n * `EncryptedKey` provides symmetric encryption and decryption of content keys\n * using various key derivation methods (HKDF, PBKDF2, Scrypt, Argon2id).\n *\n * The form of an `EncryptedKey` is an `EncryptedMessage` that contains the\n * encrypted content key, with its Additional Authenticated Data (AAD) being\n * the CBOR encoding of the key derivation method and parameters.\n *\n * CDDL:\n * ```cddl\n * EncryptedKey = #6.40027(EncryptedMessage)\n *\n * EncryptedMessage =\n * #6.40002([ ciphertext: bstr, nonce: bstr, auth: bstr, aad: bstr .cbor KeyDerivation ])\n *\n * KeyDerivation = HKDFParams / PBKDF2Params / ScryptParams / Argon2idParams\n * ```\n *\n * Ported from bc-components-rust/src/encrypted_key/encrypted_key_impl.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n createTaggedCbor,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n validateTag,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { ENCRYPTED_KEY as TAG_ENCRYPTED_KEY } from \"@bcts/tags\";\n\nimport { type SymmetricKey } from \"../symmetric/symmetric-key.js\";\nimport { EncryptedMessage } from \"../symmetric/encrypted-message.js\";\nimport { CryptoError } from \"../error.js\";\nimport { KeyDerivationMethod } from \"./key-derivation-method.js\";\nimport {\n type KeyDerivationParams,\n hkdfParams,\n pbkdf2Params,\n scryptParams,\n argon2idParams,\n keyDerivationParamsMethod,\n keyDerivationParamsToString,\n keyDerivationParamsFromCbor,\n lockWithParams,\n isPasswordBased,\n isSshAgent,\n} from \"./key-derivation-params.js\";\n\n/**\n * Encrypted key providing secure storage of symmetric keys.\n *\n * Use `lock()` to encrypt a content key with a password or secret,\n * and `unlock()` to decrypt it.\n */\nexport class EncryptedKey\n implements CborTaggedEncodable, CborTaggedDecodable<EncryptedKey>, UREncodable\n{\n private readonly _params: KeyDerivationParams;\n private readonly _encryptedMessage: EncryptedMessage;\n\n private constructor(params: KeyDerivationParams, encryptedMessage: EncryptedMessage) {\n this._params = params;\n this._encryptedMessage = encryptedMessage;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Lock (encrypt) a content key using custom derivation parameters.\n *\n * @param params - The key derivation parameters to use\n * @param secret - The secret (password or key material) to derive from\n * @param contentKey - The symmetric key to encrypt\n * @returns The encrypted key\n */\n static lockOpt(\n params: KeyDerivationParams,\n secret: Uint8Array,\n contentKey: SymmetricKey,\n ): EncryptedKey {\n const encryptedMessage = lockWithParams(params, contentKey, secret);\n return new EncryptedKey(params, encryptedMessage);\n }\n\n /**\n * Lock (encrypt) a content key using a specific derivation method with defaults.\n *\n * @param method - The key derivation method to use\n * @param secret - The secret (password or key material) to derive from\n * @param contentKey - The symmetric key to encrypt\n * @returns The encrypted key\n */\n static lock(\n method: KeyDerivationMethod,\n secret: Uint8Array,\n contentKey: SymmetricKey,\n ): EncryptedKey {\n let params: KeyDerivationParams;\n\n switch (method) {\n case KeyDerivationMethod.HKDF:\n params = hkdfParams();\n break;\n case KeyDerivationMethod.PBKDF2:\n params = pbkdf2Params();\n break;\n case KeyDerivationMethod.Scrypt:\n params = scryptParams();\n break;\n case KeyDerivationMethod.Argon2id:\n params = argon2idParams();\n break;\n case KeyDerivationMethod.SSHAgent:\n throw new Error(\n \"SSH Agent key derivation cannot be used with lock() - use lockOpt() with sshAgentParams() instead\",\n );\n }\n\n return EncryptedKey.lockOpt(params, secret, contentKey);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the encrypted message.\n */\n encryptedMessage(): EncryptedMessage {\n return this._encryptedMessage;\n }\n\n /**\n * Returns the key derivation parameters.\n */\n params(): KeyDerivationParams {\n return this._params;\n }\n\n /**\n * Returns the key derivation method.\n */\n method(): KeyDerivationMethod {\n return keyDerivationParamsMethod(this._params);\n }\n\n /**\n * Check if this uses a password-based key derivation method.\n */\n isPasswordBased(): boolean {\n return isPasswordBased(this._params);\n }\n\n /**\n * Check if this uses SSH Agent for key derivation.\n *\n * Note: SSH Agent key derivation is not yet functional in TypeScript.\n * This method is useful for detecting envelopes locked by other\n * implementations (e.g., Rust).\n */\n isSshAgent(): boolean {\n return isSshAgent(this._params);\n }\n\n /**\n * Unlock (decrypt) the content key.\n *\n * @param secret - The secret (password or key material) used to lock\n * @returns The decrypted symmetric key\n * @throws CryptoError if decryption fails (wrong password, tampered data, etc.)\n */\n unlock(secret: Uint8Array): SymmetricKey {\n // Get the AAD from the encrypted message, which contains the derivation params\n const aad = this._encryptedMessage.aad();\n if (aad.length === 0) {\n throw CryptoError.invalidData(\"Missing AAD in EncryptedKey\");\n }\n\n // Parse the derivation parameters from AAD\n const paramsCbor = decodeCbor(aad);\n const params = keyDerivationParamsFromCbor(paramsCbor);\n\n // Unlock using the parsed parameters\n switch (params.type) {\n case \"hkdf\":\n return params.params.unlock(this._encryptedMessage, secret);\n case \"pbkdf2\":\n return params.params.unlock(this._encryptedMessage, secret);\n case \"scrypt\":\n return params.params.unlock(this._encryptedMessage, secret);\n case \"argon2id\":\n return params.params.unlock(this._encryptedMessage, secret);\n case \"sshagent\":\n return params.params.unlock(this._encryptedMessage, secret);\n }\n }\n\n /**\n * Check equality with another EncryptedKey.\n */\n equals(other: EncryptedKey): boolean {\n return this._encryptedMessage.equals(other._encryptedMessage);\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `EncryptedKey(${keyDerivationParamsToString(this._params)})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with EncryptedKey.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_ENCRYPTED_KEY.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n * The EncryptedMessage is encoded with its own tag (40002).\n */\n untaggedCbor(): Cbor {\n return this._encryptedMessage.taggedCbor();\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an EncryptedKey by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): EncryptedKey {\n // The untagged content is a tagged EncryptedMessage\n const encryptedMessage = EncryptedMessage.fromTaggedCbor(cborValue);\n\n // Parse the derivation parameters from AAD\n const aad = encryptedMessage.aad();\n if (aad.length === 0) {\n throw CryptoError.invalidData(\"Missing AAD in EncryptedKey\");\n }\n const paramsCbor = decodeCbor(aad);\n const params = keyDerivationParamsFromCbor(paramsCbor);\n\n return new EncryptedKey(params, encryptedMessage);\n }\n\n /**\n * Creates an EncryptedKey by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): EncryptedKey {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): EncryptedKey {\n // Create a dummy instance for the method\n const dummyParams = hkdfParams();\n const dummyMessage = EncryptedMessage.new(\n new Uint8Array(32),\n new Uint8Array(0),\n // @ts-expect-error - Using internal method for dummy\n { data: () => new Uint8Array(12) },\n new Uint8Array(16),\n );\n const dummy = new EncryptedKey(dummyParams, dummyMessage);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): EncryptedKey {\n const cborValue = decodeCbor(data);\n return EncryptedKey.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): EncryptedKey {\n const cborValue = decodeCbor(data);\n const dummyParams = hkdfParams();\n const dummyMessage = EncryptedMessage.new(\n new Uint8Array(32),\n new Uint8Array(0),\n // @ts-expect-error - Using internal method for dummy\n { data: () => new Uint8Array(12) },\n new Uint8Array(16),\n );\n const dummy = new EncryptedKey(dummyParams, dummyMessage);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_ENCRYPTED_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_ENCRYPTED_KEY.name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates an EncryptedKey from a UR.\n */\n static fromUR(ur: UR): EncryptedKey {\n const name = TAG_ENCRYPTED_KEY.name;\n if (name === undefined) {\n throw new Error(\"TAG_ENCRYPTED_KEY.name is undefined\");\n }\n ur.checkType(name);\n return EncryptedKey.fromUntaggedCborData(ur.cbor().toData());\n }\n\n /**\n * Creates an EncryptedKey from a UR string.\n */\n static fromURString(urString: string): EncryptedKey {\n const ur = UR.fromURString(urString);\n return EncryptedKey.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * PublicKeys - Container for signing and encapsulation public keys\n *\n * PublicKeys combines a SigningPublicKey (for signature verification) and an\n * EncapsulationPublicKey (for key agreement/encryption) into a single unit.\n *\n * This is the public counterpart to PrivateKeys.\n *\n * # CBOR Serialization\n *\n * PublicKeys is serialized with tag 40017:\n * ```\n * #6.40017([<SigningPublicKey>, <EncapsulationPublicKey>])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `crypto-pubkeys`\n *\n * Ported from bc-components-rust/src/public_keys.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { PUBLIC_KEYS as TAG_PUBLIC_KEYS } from \"@bcts/tags\";\n\nimport { SigningPublicKey } from \"./signing/signing-public-key.js\";\nimport { EncapsulationPublicKey } from \"./encapsulation/encapsulation-public-key.js\";\nimport type { EncapsulationCiphertext } from \"./encapsulation/encapsulation-ciphertext.js\";\nimport type { SymmetricKey } from \"./symmetric/symmetric-key.js\";\nimport type { Signature } from \"./signing/signature.js\";\nimport type { Verifier } from \"./signing/signer.js\";\nimport type { Encrypter } from \"./encrypter.js\";\nimport { Reference, type ReferenceProvider } from \"./reference.js\";\nimport { Digest } from \"./digest.js\";\n\n/**\n * Trait for types that provide access to a PublicKeys container.\n *\n * This is useful for types that wrap or contain public keys and need\n * to provide access to the underlying key material.\n */\nexport interface PublicKeysProvider {\n /**\n * Returns the PublicKeys container.\n */\n publicKeys(): PublicKeys;\n}\n\n/**\n * PublicKeys - Container for a signing public key and an encapsulation public key.\n *\n * This type provides a convenient way to share public keys for both\n * signature verification and encryption operations.\n */\nexport class PublicKeys\n implements\n Verifier,\n Encrypter,\n ReferenceProvider,\n CborTaggedEncodable,\n CborTaggedDecodable<PublicKeys>,\n UREncodable\n{\n private readonly _signingPublicKey: SigningPublicKey;\n private readonly _encapsulationPublicKey: EncapsulationPublicKey;\n\n private constructor(\n signingPublicKey: SigningPublicKey,\n encapsulationPublicKey: EncapsulationPublicKey,\n ) {\n this._signingPublicKey = signingPublicKey;\n this._encapsulationPublicKey = encapsulationPublicKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new PublicKeys container with the given keys.\n */\n static new(\n signingPublicKey: SigningPublicKey,\n encapsulationPublicKey: EncapsulationPublicKey,\n ): PublicKeys {\n return new PublicKeys(signingPublicKey, encapsulationPublicKey);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the signing public key.\n */\n signingPublicKey(): SigningPublicKey {\n return this._signingPublicKey;\n }\n\n /**\n * Returns the encapsulation public key.\n *\n * Note: Named to match Rust's API (which has a typo but we maintain compatibility)\n */\n encapsulationPublicKey(): EncapsulationPublicKey {\n return this._encapsulationPublicKey;\n }\n\n // ============================================================================\n // Verifier Interface\n // ============================================================================\n\n /**\n * Verify a signature against a message.\n */\n verify(signature: Signature, message: Uint8Array): boolean {\n return this._signingPublicKey.verify(signature, message);\n }\n\n // ============================================================================\n // Encrypter Interface\n // ============================================================================\n\n /**\n * Encapsulate a new shared secret using the encapsulation public key.\n *\n * This implements the Encrypter interface, allowing PublicKeys to be used\n * in encryption contexts where a shared secret needs to be generated.\n *\n * @returns A tuple of [SymmetricKey, EncapsulationCiphertext]\n */\n encapsulateNewSharedSecret(): [SymmetricKey, EncapsulationCiphertext] {\n return this._encapsulationPublicKey.encapsulateNewSharedSecret();\n }\n\n // ============================================================================\n // ReferenceProvider Interface\n // ============================================================================\n\n /**\n * Returns a unique reference to this PublicKeys instance.\n *\n * The reference is derived from the SHA-256 hash of the tagged CBOR\n * representation, providing a unique, content-addressable identifier.\n */\n reference(): Reference {\n const digest = Digest.fromImage(this.taggedCborData());\n return Reference.from(digest);\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another PublicKeys.\n */\n equals(other: PublicKeys): boolean {\n return (\n this._signingPublicKey.equals(other._signingPublicKey) &&\n this._encapsulationPublicKey.equals(other._encapsulationPublicKey)\n );\n }\n\n /**\n * Get string representation.\n *\n * Format matches Rust: `PublicKeys(<short_reference>)`\n */\n toString(): string {\n return `PublicKeys(${this.reference().shortReference(\"hex\")})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with PublicKeys.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_PUBLIC_KEYS.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [<SigningPublicKey>, <EncapsulationPublicKey>]\n */\n untaggedCbor(): Cbor {\n return cbor([this._signingPublicKey.taggedCbor(), this._encapsulationPublicKey.taggedCbor()]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a PublicKeys by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): PublicKeys {\n const elements = expectArray(cborValue);\n\n if (elements.length !== 2) {\n throw new Error(`PublicKeys must have 2 elements, got ${elements.length}`);\n }\n\n const signingPublicKey = SigningPublicKey.fromTaggedCbor(elements[0]);\n const encapsulationPublicKey = EncapsulationPublicKey.fromTaggedCbor(elements[1]);\n\n return new PublicKeys(signingPublicKey, encapsulationPublicKey);\n }\n\n /**\n * Creates a PublicKeys by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): PublicKeys {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): PublicKeys {\n // We need a dummy instance to call instance methods\n // Create minimal valid keys for this purpose\n const signingKeyPrefix = new Uint8Array([0x82, 0x02, 0x58, 0x20]);\n const signingKeyData = new Uint8Array(36);\n signingKeyData.set(signingKeyPrefix, 0);\n const signingKey = SigningPublicKey.fromUntaggedCborData(signingKeyData);\n\n const encapsulationKeyPrefix = new Uint8Array([0x58, 0x20]);\n const encapsulationKeyData = new Uint8Array(34);\n encapsulationKeyData.set(encapsulationKeyPrefix, 0);\n const encapsulationKey = EncapsulationPublicKey.fromUntaggedCborData(encapsulationKeyData);\n\n const dummy = new PublicKeys(signingKey, encapsulationKey);\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): PublicKeys {\n const cborValue = decodeCbor(data);\n return PublicKeys.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): PublicKeys {\n const cborValue = decodeCbor(data);\n // We need a dummy instance to call instance methods\n const signingKeyPrefix = new Uint8Array([0x82, 0x02, 0x58, 0x20]);\n const signingKeyData = new Uint8Array(36);\n signingKeyData.set(signingKeyPrefix, 0);\n const signingKey = SigningPublicKey.fromUntaggedCborData(signingKeyData);\n\n const encapsulationKeyPrefix = new Uint8Array([0x58, 0x20]);\n const encapsulationKeyData = new Uint8Array(34);\n encapsulationKeyData.set(encapsulationKeyPrefix, 0);\n const encapsulationKey = EncapsulationPublicKey.fromUntaggedCborData(encapsulationKeyData);\n\n const dummy = new PublicKeys(signingKey, encapsulationKey);\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_PUBLIC_KEYS.name;\n if (name === undefined) {\n throw new Error(\"PUBLIC_KEYS tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a PublicKeys from a UR.\n */\n static fromUR(ur: UR): PublicKeys {\n if (ur.urTypeStr() !== TAG_PUBLIC_KEYS.name) {\n throw new Error(`Expected UR type ${TAG_PUBLIC_KEYS.name}, got ${ur.urTypeStr()}`);\n }\n // We need a dummy instance to call instance methods\n const signingKeyPrefix = new Uint8Array([0x82, 0x02, 0x58, 0x20]);\n const signingKeyData = new Uint8Array(36);\n signingKeyData.set(signingKeyPrefix, 0);\n const signingKey = SigningPublicKey.fromUntaggedCborData(signingKeyData);\n\n const encapsulationKeyPrefix = new Uint8Array([0x58, 0x20]);\n const encapsulationKeyData = new Uint8Array(34);\n encapsulationKeyData.set(encapsulationKeyPrefix, 0);\n const encapsulationKey = EncapsulationPublicKey.fromUntaggedCborData(encapsulationKeyData);\n\n const dummy = new PublicKeys(signingKey, encapsulationKey);\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a PublicKeys from a UR string.\n */\n static fromURString(urString: string): PublicKeys {\n const ur = UR.fromURString(urString);\n return PublicKeys.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * PrivateKeys - Container for signing and encapsulation private keys\n *\n * PrivateKeys combines a SigningPrivateKey (for digital signatures) and an\n * EncapsulationPrivateKey (for key agreement/encryption) into a single unit.\n *\n * # CBOR Serialization\n *\n * PrivateKeys is serialized with tag 40013:\n * ```\n * #6.40013([<SigningPrivateKey>, <EncapsulationPrivateKey>])\n * ```\n *\n * # UR Serialization\n *\n * UR type: `crypto-prvkeys`\n *\n * Ported from bc-components-rust/src/private_keys.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n cbor,\n expectArray,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { PRIVATE_KEYS as TAG_PRIVATE_KEYS } from \"@bcts/tags\";\n\nimport { SigningPrivateKey } from \"./signing/signing-private-key.js\";\nimport { EncapsulationPrivateKey } from \"./encapsulation/encapsulation-private-key.js\";\nimport { PublicKeys } from \"./public-keys.js\";\nimport type { SymmetricKey } from \"./symmetric/symmetric-key.js\";\nimport type { EncapsulationCiphertext } from \"./encapsulation/encapsulation-ciphertext.js\";\nimport type { Signature } from \"./signing/signature.js\";\nimport type { Signer } from \"./signing/signer.js\";\nimport type { SigningOptions } from \"./signing/signature-scheme.js\";\nimport type { Decrypter } from \"./encrypter.js\";\nimport { Reference, type ReferenceProvider } from \"./reference.js\";\nimport { Digest } from \"./digest.js\";\n\n/**\n * Trait for types that provide access to a PrivateKeys container.\n *\n * This is useful for types that wrap or contain private keys and need\n * to provide access to the underlying key material.\n */\nexport interface PrivateKeysProvider {\n /**\n * Returns the PrivateKeys container.\n */\n privateKeys(): PrivateKeys;\n}\n\n/**\n * PrivateKeys - Container for a signing key and an encapsulation key.\n *\n * This type provides a convenient way to manage a pair of private keys\n * for both signing and encryption operations.\n */\nexport class PrivateKeys\n implements\n Signer,\n Decrypter,\n ReferenceProvider,\n CborTaggedEncodable,\n CborTaggedDecodable<PrivateKeys>,\n UREncodable\n{\n private readonly _signingPrivateKey: SigningPrivateKey;\n private readonly _encapsulationPrivateKey: EncapsulationPrivateKey;\n\n private constructor(\n signingPrivateKey: SigningPrivateKey,\n encapsulationPrivateKey: EncapsulationPrivateKey,\n ) {\n this._signingPrivateKey = signingPrivateKey;\n this._encapsulationPrivateKey = encapsulationPrivateKey;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new PrivateKeys container with the given keys.\n */\n static withKeys(\n signingPrivateKey: SigningPrivateKey,\n encapsulationPrivateKey: EncapsulationPrivateKey,\n ): PrivateKeys {\n return new PrivateKeys(signingPrivateKey, encapsulationPrivateKey);\n }\n\n /**\n * Create a new PrivateKeys container with random Ed25519/X25519 keys.\n */\n static new(): PrivateKeys {\n const signingKey = SigningPrivateKey.random();\n const encapsulationKey = EncapsulationPrivateKey.random();\n return new PrivateKeys(signingKey, encapsulationKey);\n }\n\n /**\n * Generate a new PrivateKeys container with random Ed25519/X25519 keys.\n * This is an alias for new() for API compatibility.\n */\n static generate(): PrivateKeys {\n return PrivateKeys.new();\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the signing private key.\n */\n signingPrivateKey(): SigningPrivateKey {\n return this._signingPrivateKey;\n }\n\n /**\n * Returns the encapsulation private key.\n *\n * Note: Named to match Rust's API (which has a typo but we maintain compatibility)\n */\n encapsulationPrivateKey(): EncapsulationPrivateKey {\n return this._encapsulationPrivateKey;\n }\n\n /**\n * Derive the corresponding public keys.\n */\n publicKeys(): PublicKeys {\n const signingPublicKey = this._signingPrivateKey.publicKey();\n const encapsulationPublicKey = this._encapsulationPrivateKey.publicKey();\n return PublicKeys.new(signingPublicKey, encapsulationPublicKey);\n }\n\n // ============================================================================\n // Signer Interface\n // ============================================================================\n\n /**\n * Sign a message with optional signing options using the signing private key.\n */\n signWithOptions(message: Uint8Array, options?: SigningOptions): Signature {\n return this._signingPrivateKey.signWithOptions(message, options);\n }\n\n /**\n * Sign a message using the signing private key.\n */\n sign(message: Uint8Array): Signature {\n return this._signingPrivateKey.sign(message);\n }\n\n // ============================================================================\n // Decrypter Interface\n // ============================================================================\n\n /**\n * Decapsulate a shared secret from a ciphertext.\n *\n * This implements the Decrypter interface, allowing PrivateKeys to be used\n * in encryption contexts where a shared secret needs to be recovered.\n */\n decapsulateSharedSecret(ciphertext: EncapsulationCiphertext): SymmetricKey {\n return this._encapsulationPrivateKey.decapsulateSharedSecret(ciphertext);\n }\n\n // ============================================================================\n // ReferenceProvider Interface\n // ============================================================================\n\n /**\n * Returns a unique reference to this PrivateKeys instance.\n *\n * The reference is derived from the SHA-256 hash of the tagged CBOR\n * representation, providing a unique, content-addressable identifier.\n */\n reference(): Reference {\n const digest = Digest.fromImage(this.taggedCborData());\n return Reference.from(digest);\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another PrivateKeys.\n */\n equals(other: PrivateKeys): boolean {\n return (\n this._signingPrivateKey.equals(other._signingPrivateKey) &&\n this._encapsulationPrivateKey.equals(other._encapsulationPrivateKey)\n );\n }\n\n /**\n * Get string representation.\n *\n * Format matches Rust: `PrivateKeys(<short_reference>)`\n */\n toString(): string {\n return `PrivateKeys(${this.reference().shortReference(\"hex\")})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with PrivateKeys.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_PRIVATE_KEYS.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n *\n * Format: [<SigningPrivateKey>, <EncapsulationPrivateKey>]\n */\n untaggedCbor(): Cbor {\n return cbor([this._signingPrivateKey.taggedCbor(), this._encapsulationPrivateKey.taggedCbor()]);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a PrivateKeys by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): PrivateKeys {\n const elements = expectArray(cborValue);\n\n if (elements.length !== 2) {\n throw new Error(`PrivateKeys must have 2 elements, got ${elements.length}`);\n }\n\n const signingPrivateKey = SigningPrivateKey.fromTaggedCbor(elements[0]);\n const encapsulationPrivateKey = EncapsulationPrivateKey.fromTaggedCbor(elements[1]);\n\n return new PrivateKeys(signingPrivateKey, encapsulationPrivateKey);\n }\n\n /**\n * Creates a PrivateKeys by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): PrivateKeys {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): PrivateKeys {\n // Create a dummy instance for accessing instance methods\n const dummy = PrivateKeys.new();\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): PrivateKeys {\n const cborValue = decodeCbor(data);\n return PrivateKeys.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): PrivateKeys {\n const cborValue = decodeCbor(data);\n const dummy = PrivateKeys.new();\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_PRIVATE_KEYS.name;\n if (name === undefined) {\n throw new Error(\"PRIVATE_KEYS tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a PrivateKeys from a UR.\n */\n static fromUR(ur: UR): PrivateKeys {\n if (ur.urTypeStr() !== TAG_PRIVATE_KEYS.name) {\n throw new Error(`Expected UR type ${TAG_PRIVATE_KEYS.name}, got ${ur.urTypeStr()}`);\n }\n const dummy = PrivateKeys.new();\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a PrivateKeys from a UR string.\n */\n static fromURString(urString: string): PrivateKeys {\n const ur = UR.fromURString(urString);\n return PrivateKeys.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * PrivateKeyBase - Root cryptographic material for deterministic key derivation\n *\n * PrivateKeyBase is a 32-byte value that serves as the root of cryptographic\n * material from which various keys can be deterministically derived.\n *\n * # CBOR Serialization\n *\n * PrivateKeyBase is serialized with tag 40016:\n * ```\n * #6.40016(h'<32-byte-key-material>')\n * ```\n *\n * # UR Serialization\n *\n * UR type: `crypto-prvkey-base`\n *\n * Ported from bc-components-rust/src/private_key_base.rs\n */\n\nimport { SecureRandomNumberGenerator, type RandomNumberGenerator } from \"@bcts/rand\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { PRIVATE_KEY_BASE as TAG_PRIVATE_KEY_BASE } from \"@bcts/tags\";\nimport { hkdfHmacSha256 } from \"@bcts/crypto\";\n\nimport { X25519PrivateKey } from \"./x25519/x25519-private-key.js\";\nimport { Ed25519PrivateKey } from \"./ed25519/ed25519-private-key.js\";\nimport { ECPrivateKey } from \"./ec-key/ec-private-key.js\";\nimport { SigningPrivateKey } from \"./signing/signing-private-key.js\";\nimport { EncapsulationPrivateKey } from \"./encapsulation/encapsulation-private-key.js\";\nimport { bytesToHex } from \"./utils.js\";\nimport { PrivateKeys } from \"./private-keys.js\";\nimport type { PublicKeys } from \"./public-keys.js\";\n\n/** Default size of PrivateKeyBase key material in bytes (used for random generation) */\nconst PRIVATE_KEY_BASE_DEFAULT_SIZE = 32;\n\n/** Key derivation salt string - must match Rust's bc-crypto derive functions */\nconst SALT_SIGNING = \"signing\";\n\n/**\n * PrivateKeyBase - Root cryptographic material for deterministic key derivation.\n *\n * This is the foundation from which signing keys and agreement keys can be\n * deterministically derived using HKDF.\n */\nexport class PrivateKeyBase\n implements CborTaggedEncodable, CborTaggedDecodable<PrivateKeyBase>, UREncodable\n{\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length === 0) {\n throw new Error(\"PrivateKeyBase must have non-zero length\");\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a new random PrivateKeyBase.\n */\n static new(): PrivateKeyBase {\n const rng = new SecureRandomNumberGenerator();\n return PrivateKeyBase.newUsing(rng);\n }\n\n /**\n * Create a new random PrivateKeyBase using the provided RNG.\n */\n static newUsing(rng: RandomNumberGenerator): PrivateKeyBase {\n const data = rng.randomData(PRIVATE_KEY_BASE_DEFAULT_SIZE);\n return new PrivateKeyBase(data);\n }\n\n /**\n * Create a PrivateKeyBase from raw bytes.\n *\n * @param data - 32 bytes of key material\n */\n static fromData(data: Uint8Array): PrivateKeyBase {\n return new PrivateKeyBase(data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Returns the raw key material.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw key material.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n // ============================================================================\n // Key Derivation Methods\n // ============================================================================\n\n /**\n * Derive an Ed25519 signing private key.\n *\n * Uses HKDF with salt \"signing\", matching Rust's derive_signing_private_key().\n */\n ed25519SigningPrivateKey(): SigningPrivateKey {\n const derivedKey = this._deriveKey(SALT_SIGNING);\n const ed25519Key = Ed25519PrivateKey.from(derivedKey);\n return SigningPrivateKey.newEd25519(ed25519Key);\n }\n\n /**\n * Derive an X25519 agreement private key.\n *\n * Uses HKDF with salt \"agreement\", matching Rust's derive_agreement_private_key().\n */\n x25519PrivateKey(): X25519PrivateKey {\n return X25519PrivateKey.deriveFromKeyMaterial(this._data);\n }\n\n /**\n * Get EncapsulationPrivateKey for decryption.\n *\n * Returns the derived X25519 private key wrapped as EncapsulationPrivateKey.\n */\n encapsulationPrivateKey(): EncapsulationPrivateKey {\n return EncapsulationPrivateKey.fromX25519PrivateKey(this.x25519PrivateKey());\n }\n\n /**\n * Derive a PrivateKeys container with Ed25519 signing and X25519 agreement keys.\n *\n * @returns PrivateKeys containing the derived signing and encapsulation keys\n */\n ed25519PrivateKeys(): PrivateKeys {\n return PrivateKeys.withKeys(this.ed25519SigningPrivateKey(), this.encapsulationPrivateKey());\n }\n\n /**\n * Derive a PublicKeys container from the derived keys.\n *\n * @returns PublicKeys containing the derived public keys\n */\n ed25519PublicKeys(): PublicKeys {\n const privateKeys = this.ed25519PrivateKeys();\n return privateKeys.publicKeys();\n }\n\n /**\n * Derive a Schnorr signing private key.\n *\n * Uses ECPrivateKey.deriveFromKeyMaterial() matching Rust's\n * PrivateKeyBase::schnorr_signing_private_key().\n */\n schnorrSigningPrivateKey(): SigningPrivateKey {\n const ecKey = ECPrivateKey.deriveFromKeyMaterial(this._data);\n return SigningPrivateKey.newSchnorr(ecKey);\n }\n\n /**\n * Derive a PrivateKeys container with Schnorr signing and X25519 agreement keys.\n *\n * Matches Rust's PrivateKeyBase::schnorr_private_keys().\n */\n schnorrPrivateKeys(): PrivateKeys {\n return PrivateKeys.withKeys(this.schnorrSigningPrivateKey(), this.encapsulationPrivateKey());\n }\n\n /**\n * Derive a PublicKeys container from Schnorr derived keys.\n */\n schnorrPublicKeys(): PublicKeys {\n return this.schnorrPrivateKeys().publicKeys();\n }\n\n /**\n * Derive an ECDSA signing private key.\n *\n * Uses ECPrivateKey.deriveFromKeyMaterial() matching Rust's\n * PrivateKeyBase::ecdsa_signing_private_key().\n */\n ecdsaSigningPrivateKey(): SigningPrivateKey {\n const ecKey = ECPrivateKey.deriveFromKeyMaterial(this._data);\n return SigningPrivateKey.newEcdsa(ecKey);\n }\n\n /**\n * Derive a PrivateKeys container with ECDSA signing and X25519 agreement keys.\n *\n * Matches Rust's PrivateKeyBase::ecdsa_private_keys().\n */\n ecdsaPrivateKeys(): PrivateKeys {\n return PrivateKeys.withKeys(this.ecdsaSigningPrivateKey(), this.encapsulationPrivateKey());\n }\n\n /**\n * Derive a PublicKeys container from ECDSA derived keys.\n */\n ecdsaPublicKeys(): PublicKeys {\n return this.ecdsaPrivateKeys().publicKeys();\n }\n\n /**\n * Internal key derivation using HKDF-SHA256.\n * Matches Rust's hkdf_hmac_sha256(key_material, salt, key_len) with empty info.\n */\n private _deriveKey(salt: string): Uint8Array {\n return hkdfHmacSha256(this._data, new TextEncoder().encode(salt), 32);\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another PrivateKeyBase.\n */\n equals(other: PrivateKeyBase): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation (truncated for security).\n */\n toString(): string {\n const hex = bytesToHex(this._data);\n return `PrivateKeyBase(${hex.substring(0, 8)}...)`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with PrivateKeyBase.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_PRIVATE_KEY_BASE.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a PrivateKeyBase by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): PrivateKeyBase {\n const data = expectBytes(cborValue);\n return PrivateKeyBase.fromData(data);\n }\n\n /**\n * Creates a PrivateKeyBase by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cborValue: Cbor): PrivateKeyBase {\n validateTag(cborValue, this.cborTags());\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): PrivateKeyBase {\n const dummy = new PrivateKeyBase(new Uint8Array(PRIVATE_KEY_BASE_DEFAULT_SIZE));\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): PrivateKeyBase {\n const cborValue = decodeCbor(data);\n return PrivateKeyBase.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): PrivateKeyBase {\n const cborValue = decodeCbor(data);\n const dummy = new PrivateKeyBase(new Uint8Array(PRIVATE_KEY_BASE_DEFAULT_SIZE));\n return dummy.fromUntaggedCbor(cborValue);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation.\n */\n ur(): UR {\n const name = TAG_PRIVATE_KEY_BASE.name;\n if (name === undefined) {\n throw new Error(\"PRIVATE_KEY_BASE tag name is undefined\");\n }\n return UR.new(name, this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a PrivateKeyBase from a UR.\n */\n static fromUR(ur: UR): PrivateKeyBase {\n if (ur.urTypeStr() !== TAG_PRIVATE_KEY_BASE.name) {\n throw new Error(`Expected UR type ${TAG_PRIVATE_KEY_BASE.name}, got ${ur.urTypeStr()}`);\n }\n const dummy = new PrivateKeyBase(new Uint8Array(PRIVATE_KEY_BASE_DEFAULT_SIZE));\n return dummy.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a PrivateKeyBase from a UR string.\n */\n static fromURString(urString: string): PrivateKeyBase {\n const ur = UR.fromURString(urString);\n return PrivateKeyBase.fromUR(ur);\n }\n}\n","/**\n * Copyright © 2023-2026 Blockchain Commons, LLC\n * Copyright © 2025-2026 Parity Technologies\n *\n *\n * SSKR Integration - CBOR wrappers for SSKR shares\n *\n * This module provides CBOR serialization for SSKR (Sharded Secret Key\n * Reconstruction) shares. It wraps the core SSKR functionality from\n * @bcts/sskr with CBOR tags.\n *\n * # CBOR Serialization\n *\n * SSKRShare is serialized with tag 40309:\n * ```\n * #6.40309(h'<share-bytes>')\n * ```\n *\n * Legacy tag 309 is also supported for reading.\n *\n * Ported from bc-components-rust/src/sskr_mod.rs\n */\n\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n tagValue,\n} from \"@bcts/dcbor\";\nimport { SSKR_SHARE as TAG_SSKR_SHARE, SSKR_SHARE_V1 as TAG_SSKR_SHARE_V1 } from \"@bcts/tags\";\n\nimport { bytesToHex, hexToBytes } from \"./utils.js\";\nimport {\n sskrGenerate,\n sskrGenerateUsing,\n sskrCombine,\n Secret as SSKRSecret,\n GroupSpec as SSKRGroupSpec,\n Spec as SSKRSpec,\n} from \"@bcts/sskr\";\nimport type { RandomNumberGenerator } from \"@bcts/rand\";\n\n// Re-export from sskr package\nexport { sskrGenerate, sskrGenerateUsing, sskrCombine, SSKRSecret, SSKRGroupSpec, SSKRSpec };\n\n/** Metadata size in bytes (identifier + thresholds + indices) */\nconst METADATA_SIZE_BYTES = 5;\n\n/**\n * SSKRShareCbor - CBOR/UR wrapper for an SSKR share.\n *\n * An SSKR share is a binary encoding of:\n * - Identifier (2 bytes)\n * - Group metadata (1 byte): group_threshold-1 (4 bits) + group_count-1 (4 bits)\n * - Member metadata (1 byte): group_index (4 bits) + member_threshold-1 (4 bits)\n * - Member index (1 byte): reserved (4 bits, must be 0) + member_index (4 bits)\n * - Share value (variable length)\n */\nexport class SSKRShareCbor implements CborTaggedEncodable, CborTaggedDecodable<SSKRShareCbor> {\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length < METADATA_SIZE_BYTES) {\n throw new Error(\n `SSKRShare must be at least ${METADATA_SIZE_BYTES} bytes, got ${data.length}`,\n );\n }\n this._data = new Uint8Array(data);\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create an SSKRShareCbor from raw share bytes.\n *\n * @param data - The share bytes (5+ bytes)\n */\n static fromData(data: Uint8Array): SSKRShareCbor {\n return new SSKRShareCbor(data);\n }\n\n /**\n * Create an SSKRShareCbor from a hex string.\n *\n * @param hex - The share as a hex string\n */\n static fromHex(hex: string): SSKRShareCbor {\n return new SSKRShareCbor(hexToBytes(hex));\n }\n\n // ============================================================================\n // Instance Methods - Data Access\n // ============================================================================\n\n /**\n * Returns the raw share bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Returns a copy of the raw share bytes.\n */\n data(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Returns the share as a hex string.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n // ============================================================================\n // Instance Methods - Metadata Access\n // ============================================================================\n\n /**\n * Returns the identifier (2 bytes) as a number.\n */\n identifier(): number {\n return (this._data[0] << 8) | this._data[1];\n }\n\n /**\n * Returns the identifier as a hex string.\n */\n identifierHex(): string {\n return bytesToHex(this._data.subarray(0, 2));\n }\n\n /**\n * Returns the group threshold (minimum number of groups needed).\n */\n groupThreshold(): number {\n return (this._data[2] >> 4) + 1;\n }\n\n /**\n * Returns the total number of groups.\n */\n groupCount(): number {\n return (this._data[2] & 0x0f) + 1;\n }\n\n /**\n * Returns this share's group index (0-based).\n */\n groupIndex(): number {\n return this._data[3] >> 4;\n }\n\n /**\n * Returns the member threshold for this share's group.\n */\n memberThreshold(): number {\n return (this._data[3] & 0x0f) + 1;\n }\n\n /**\n * Returns this share's member index within its group (0-based).\n */\n memberIndex(): number {\n return this._data[4] & 0x0f;\n }\n\n /**\n * Returns the share value (the actual secret share data).\n */\n shareValue(): Uint8Array {\n return this._data.subarray(METADATA_SIZE_BYTES);\n }\n\n // ============================================================================\n // Equality and String Representation\n // ============================================================================\n\n /**\n * Compare with another SSKRShareCbor.\n */\n equals(other: SSKRShareCbor): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `SSKRShare(${this.identifierHex()}, group ${this.groupIndex() + 1}/${this.groupCount()}, member ${this.memberIndex() + 1}/${this.memberThreshold()})`;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with SSKRShare.\n * Includes both current tag (40309) and legacy tag (309) for compatibility.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_SSKR_SHARE.value, TAG_SSKR_SHARE_V1.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding.\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates an SSKRShareCbor by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cborValue: Cbor): SSKRShareCbor {\n const data = expectBytes(cborValue);\n return SSKRShareCbor.fromData(data);\n }\n\n /**\n * Creates an SSKRShareCbor by decoding it from tagged CBOR.\n * Accepts both tag 40309 and legacy tag 309.\n */\n fromTaggedCbor(cborValue: Cbor): SSKRShareCbor {\n const tag = tagValue(cborValue);\n\n // Accept both current and legacy tags\n if (tag !== TAG_SSKR_SHARE.value && tag !== TAG_SSKR_SHARE_V1.value) {\n throw new Error(\n `Invalid SSKRShare tag: expected ${TAG_SSKR_SHARE.value} or ${TAG_SSKR_SHARE_V1.value}, got ${tag}`,\n );\n }\n\n const content = extractTaggedContent(cborValue);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cborValue: Cbor): SSKRShareCbor {\n const dummy = new SSKRShareCbor(new Uint8Array(METADATA_SIZE_BYTES + 16));\n return dummy.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): SSKRShareCbor {\n const cborValue = decodeCbor(data);\n return SSKRShareCbor.fromTaggedCbor(cborValue);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): SSKRShareCbor {\n const cborValue = decodeCbor(data);\n const dummy = new SSKRShareCbor(new Uint8Array(METADATA_SIZE_BYTES + 16));\n return dummy.fromUntaggedCbor(cborValue);\n }\n}\n\n// ============================================================================\n// Type Alias for Rust Parity\n// ============================================================================\n\n/**\n * SSKRShare - Alias for SSKRShareCbor to match Rust API naming.\n *\n * In Rust, this type is called `SSKRShare`. The TypeScript implementation\n * uses `SSKRShareCbor` to distinguish it from raw share data, but we provide\n * this alias for API parity with bc-components-rust.\n */\nexport type SSKRShare = SSKRShareCbor;\n\n/**\n * Create an SSKRShare from raw data.\n * This is a convenience function that matches the Rust constructor pattern.\n */\n// eslint-disable-next-line no-redeclare -- Intentional: TypeScript allows type/value with same name\nexport const SSKRShare = {\n fromData: (data: Uint8Array): SSKRShareCbor => SSKRShareCbor.fromData(data),\n fromHex: (hex: string): SSKRShareCbor => SSKRShareCbor.fromHex(hex),\n fromTaggedCbor: (cborValue: Cbor): SSKRShareCbor => SSKRShareCbor.fromTaggedCbor(cborValue),\n fromTaggedCborData: (data: Uint8Array): SSKRShareCbor => SSKRShareCbor.fromTaggedCborData(data),\n fromUntaggedCborData: (data: Uint8Array): SSKRShareCbor =>\n SSKRShareCbor.fromUntaggedCborData(data),\n};\n\n// ============================================================================\n// Wrapper Functions (Rust API Parity)\n// ============================================================================\n\n/**\n * Generates SSKR shares for the given spec and secret.\n *\n * This function matches the Rust `sskr_generate` API by returning wrapped\n * SSKRShare objects instead of raw byte arrays.\n *\n * @param spec - The SSKRSpec instance defining group/member thresholds\n * @param masterSecret - The SSKRSecret to be split into shares\n * @returns Nested array of SSKRShare instances (groups × members)\n *\n * @example\n * ```typescript\n * import { SSKRSecret, SSKRSpec, SSKRGroupSpec, sskrGenerateShares } from '@bcts/components';\n *\n * const secret = SSKRSecret.new(new Uint8Array(16).fill(0x42));\n * const group = SSKRGroupSpec.new(2, 3); // 2 of 3\n * const spec = SSKRSpec.new(1, [group]); // 1 group required\n *\n * const shares = sskrGenerateShares(spec, secret);\n * // shares[0] contains 3 SSKRShare instances\n * ```\n */\nexport function sskrGenerateShares(spec: SSKRSpec, masterSecret: SSKRSecret): SSKRShare[][] {\n const rawGroups = sskrGenerate(spec, masterSecret);\n return rawGroups.map((group) => group.map((shareData) => SSKRShareCbor.fromData(shareData)));\n}\n\n/**\n * Interface for RNG that only requires fillRandomData method.\n * This is a subset of the full RandomNumberGenerator interface.\n */\nexport interface SimpleRng {\n fillRandomData(data: Uint8Array): void;\n}\n\n/**\n * Generates SSKR shares using a custom random number generator.\n *\n * This function matches the Rust `sskr_generate_using` API by returning\n * wrapped SSKRShare objects and allowing a custom RNG for deterministic\n * testing.\n *\n * @param spec - The SSKRSpec instance defining group/member thresholds\n * @param masterSecret - The SSKRSecret to be split into shares\n * @param rng - Random number generator (must have fillRandomData method)\n * @returns Nested array of SSKRShare instances (groups × members)\n */\nexport function sskrGenerateSharesUsing(\n spec: SSKRSpec,\n masterSecret: SSKRSecret,\n rng: SimpleRng,\n): SSKRShare[][] {\n // Cast to RandomNumberGenerator - sskrGenerateUsing only uses fillRandomData internally\n const rawGroups = sskrGenerateUsing(spec, masterSecret, rng as unknown as RandomNumberGenerator);\n return rawGroups.map((group) => group.map((shareData) => SSKRShareCbor.fromData(shareData)));\n}\n\n/**\n * Combines SSKR shares to reconstruct the original secret.\n *\n * This function matches the Rust `sskr_combine` API by accepting\n * wrapped SSKRShare objects.\n *\n * @param shares - Array of SSKRShare instances to combine\n * @returns The reconstructed SSKRSecret\n * @throws Error if shares cannot be combined (insufficient shares, mismatched IDs, etc.)\n *\n * @example\n * ```typescript\n * import { sskrGenerateShares, sskrCombineShares } from '@bcts/components';\n *\n * // Generate shares\n * const shares = sskrGenerateShares(spec, secret);\n *\n * // Combine 2 shares from the first group\n * const recoveredSecret = sskrCombineShares([shares[0][0], shares[0][1]]);\n * ```\n */\nexport function sskrCombineShares(shares: SSKRShare[]): SSKRSecret {\n const rawShares = shares.map((share) => share.data());\n return ssk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