UNPKG

noble-curves-extended

Version:

This project extends @noble/curves to allow randomBytes to be specified externally

1,130 lines (1,029 loc) 67.3 kB
import * as asn1js from 'asn1js'; import { CHash } from '@noble/curves/abstract/utils'; import { CurveFn as CurveFn_2 } from '@noble/curves/abstract/edwards'; import { CurveFn as CurveFn_3 } from '@noble/curves/abstract/weierstrass'; import { CurveFn as CurveFn_4 } from '@noble/curves/abstract/montgomery'; import { CurveType as CurveType_2 } from '@noble/curves/abstract/weierstrass'; import { IField } from '@noble/curves/abstract/modular'; import { RecoveredSignatureType } from '@noble/curves/abstract/weierstrass'; import { SignatureType } from '@noble/curves/abstract/weierstrass'; export declare function adjustScalarBytes(bytes: Uint8Array): Uint8Array; /** * Asserts min <= n < max. NOTE: It's < max and not <= max. * @example * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n) */ export declare function aInRange(title: string, n: bigint, min: bigint, max: bigint): void; /** * Converts an algorithm name to its corresponding curve name. * Supports ES256, ES384, ES512, and ES256K algorithms. * Returns undefined when the algorithm cannot uniquely determine a curve name (e.g., EdDSA can map to Ed25519 or Ed448). * @typedef {Function} AlgorithmToCurveName * @param {string} algorithmName - The algorithm name (e.g., 'ES256', 'ES384', 'ES512', 'ES256K') * @returns {string|undefined} The corresponding curve name, or undefined if the curve name cannot be uniquely determined from the algorithm */ export declare const algorithmToCurveName: (algorithmName: string) => string | undefined; export declare const bls12381Fr: IField<bigint>; /** * Computes the thumbprint JSON for an EC (Elliptic Curve) public key. * The thumbprint JSON is a canonical JSON representation containing only the required fields: crv, kty, x, and y. * @typedef {Function} ComputeEcThumbprintJSON * @param {JwkPublicKey} jwk - The JWK public key with kty='EC' * @returns {string} The canonical JSON string representation of the EC key thumbprint * @throws {Error} Throws an error if: * - kty is not 'EC' * - crv is missing * - x is missing * - y is missing */ export declare const computeEcThumbprintJSON: (jwk: JwkPublicKey) => string; /** * Computes the JWK thumbprint as a SHA-256 hash. * The thumbprint is computed by first generating the canonical JSON representation of the key, * then computing the SHA-256 hash of the UTF-8 encoded JSON string. * @typedef {Function} ComputeJwkThumbprint * @param {JwkPublicKey} jwk - The JWK public key with kty='EC' or kty='OKP' * @returns {Uint8Array} The SHA-256 hash of the thumbprint JSON as a byte array * @throws {Error} Throws an error if kty is not 'EC' or 'OKP', or if required parameters are missing */ export declare const computeJwkThumbprint: (jwk: JwkPublicKey) => Uint8Array; /** * Computes the thumbprint JSON for a JWK public key. * Supports EC (Elliptic Curve) and OKP (Octet Key Pair) key types. * @typedef {Function} ComputeJwkThumbprintJSON * @param {JwkPublicKey} jwk - The JWK public key with kty='EC' or kty='OKP' * @returns {string} The canonical JSON string representation of the key thumbprint * @throws {Error} Throws an error if kty is not 'EC' or 'OKP' */ export declare const computeJwkThumbprintJSON: (jwk: JwkPublicKey) => string; /** * Computes the thumbprint JSON for an OKP (Octet Key Pair) public key. * The thumbprint JSON is a canonical JSON representation containing only the required fields: crv, kty, and x. * @typedef {Function} ComputeOkpThumbprintJSON * @param {JwkPublicKey} jwk - The JWK public key with kty='OKP' * @returns {string} The canonical JSON string representation of the OKP key thumbprint * @throws {Error} Throws an error if: * - kty is not 'OKP' * - crv is missing * - x is missing */ export declare const computeOkpThumbprintJSON: (jwk: JwkPublicKey) => string; export declare const createBls12_381: (randomBytes: RandomBytes) => { utils: { randomPrivateKey: () => Uint8Array; }; }; /** * Creates a curve function with the ability to generate curves using custom hash functions. * The function returns a curve function that includes a create method for generating curves with custom hash functions. * * @param curveDef - The curve definition excluding hash-related properties * @param hash - The default hash function to use * @param randomBytes - The random bytes function to use * @returns A curve function with an additional create method for generating curves with custom hash functions */ export declare function createCurve(curveDef: CurveDef, hash: CHash, randomBytes: RandomBytes): CurveFn_3; /** * Creates an ECDH curve instance based on the specified curve name. * * @param {string} curveName - The name of the curve to use for ECDH. Supported values: 'P-256', 'P-384', 'P-521', 'secp256k1', 'X25519'. * @param {RandomBytes} randomBytes - A function to generate random bytes. * @returns {EcdhCurve} An ECDH curve instance for the specified curve. * @throws {Error} Throws an error if the curve name is unsupported. */ export declare const createEcdhCurve: (curveName: string, randomBytes: RandomBytes) => EcdhCurve; /** * ed25519 curve with EdDSA signatures. */ export declare const createEd25519: (randomBytes: RandomBytes) => CurveFn_2; /** * Creates a HMAC function using the provided hash function. * The function generates HMAC for the concatenated messages using the provided key. * * @param hash - The hash function to use for HMAC generation * @returns A function that generates HMAC for the concatenated messages */ export declare const createHmacFn: (hash: CHash) => (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array<ArrayBufferLike>; /** NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods. */ export declare const createP256: (randomBytes: RandomBytes) => CurveFn_3; /** NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. */ export declare const createP384: (randomBytes: RandomBytes) => CurveFn_3; /** NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. */ export declare const createP521: (randomBytes: RandomBytes) => CurveFn_3; /** * secp256k1 curve, ECDSA and ECDH methods. * * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n` * * @example * ```js * import { secp256k1 } from '@noble/curves/secp256k1'; * const priv = secp256k1.utils.randomPrivateKey(); * const pub = secp256k1.getPublicKey(priv); * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available * const isValid = secp256k1.verify(sig, msg, pub) === true; * ``` */ export declare const createSecp256k1: (randomBytes: RandomBytes) => CurveFn_3; /** * Creates a signature curve instance based on the specified curve name. * * @param {string} curveName - The name of the curve to use for the signature. Supported values: 'P-256', 'P-384', 'P-521', 'secp256k1', 'Ed25519'. * @param {RandomBytes} randomBytes - A function to generate random bytes. * @returns {SignatureCurve} A signature curve instance for the specified curve. * @throws {Error} Throws an error if the curve name is unsupported. */ export declare const createSignatureCurve: (curveName: string, randomBytes: RandomBytes) => SignatureCurve; /** * Creates a signature curve instance with RNG operations disabled. * This function creates a signature curve where random number generation * operations (randomBytes, randomPrivateKey) are not available. * * @param {string} curveName - The name of the curve to use for the signature. Supported values: 'P-256', 'P-384', 'P-521', 'secp256k1', 'Ed25519'. * @returns {Omit<SignatureCurve, 'randomBytes' | 'randomPrivateKey'>} A signature curve instance with RNG operations omitted. * @throws {Error} Throws an error if the curve name is unsupported. */ export declare const createSignatureCurveRngDisallowed: (curveName: string) => Omit<SignatureCurve, "randomBytes" | "randomPrivateKey">; export declare const createX25519: (randomBytes: RandomBytes) => CurveFn; /** * Type definition for curve configuration, excluding hash-related properties. * Matches the API of @noble/hashes but allows creating curves with custom hash functions. */ export declare type CurveDef = Readonly<Omit<CurveType_2, 'hash' | 'hmac' | 'randomBytes'>>; export declare type CurveFn = { CURVE: CurveType; scalarMult: (scalar: Hex, u: Hex) => Uint8Array; scalarMultBase: (scalar: Hex) => Uint8Array; getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array; getPublicKey: (privateKey: Hex) => Uint8Array; utils: { randomPrivateKey: () => Uint8Array; }; GuBytes: Uint8Array; }; /** * Represents the names of supported cryptographic curves. * @typedef {('P-256' | 'P-384' | 'P-521' | 'secp256k1' | 'Ed25519' | 'X25519')} CurveName */ export declare type CurveName = 'P-256' | 'P-384' | 'P-521' | 'secp256k1' | 'Ed25519' | 'X25519'; /** * Converts a curve name to its corresponding algorithm name. * Supports P-256, P-384, P-521, secp256k1, Ed25519, and X25519 curves. * Returns undefined when the curve name cannot uniquely determine an algorithm name. * @typedef {Function} CurveToAlgorithmName * @param {string} curveName - The curve name (e.g., 'P-256', 'P-384', 'P-521', 'secp256k1', 'Ed25519', 'X25519') * @returns {string|undefined} The corresponding algorithm name, or undefined if the algorithm name cannot be uniquely determined from the curve */ export declare const curveToAlgorithmName: (curveName: string) => string | undefined; export declare type CurveType = { P: bigint; type: 'x25519' | 'x448'; adjustScalarBytes: (bytes: Uint8Array) => Uint8Array; powPminus2: (x: bigint) => bigint; randomBytes?: (bytesLength?: number) => Uint8Array; }; /** * Interface for Elliptic Curve Diffie-Hellman (ECDH) operations. * Extends UnifiedBase with a method to generate a shared secret. * @interface Ecdh * @extends UnifiedBase * @property {GetSharedSecret} getSharedSecret - Function to generate a shared secret */ export declare interface EcdhCurve extends UnifiedBase { getSharedSecret: GetSharedSecret; } /** * Represents the names of curves used for ECDH operations. * Excludes 'Ed25519' as it is not used for ECDH. * @typedef {Exclude<CurveName, 'Ed25519'>} EcdhCurveName */ export declare type EcdhCurveName = Exclude<CurveName, 'Ed25519'>; export declare const ed25519_CURVE: EdwardsOpts; export declare function ed25519_pow_2_252_3(x: bigint): { pow_p_5_8: bigint; b2: bigint; }; /** * Edwards implementation for digital signatures. * This class provides a high-level interface for Edwards operations, including * key generation, validation, signing, verification, and JWK/raw conversions. * * @example * ```typescript * const edwards = new Edwards({ * curve, * randomBytes, * curveName: 'ed25519', * signatureAlgorithmName: 'EdDSA', * keyByteLength: 32, * }); * const privateKey = edwards.randomPrivateKey(); * const publicKey = edwards.getPublicKey(privateKey); * const message = new TextEncoder().encode('hello'); * const signature = edwards.sign({ message, privateKey }); * const isValid = edwards.verify({ signature, message, publicKey }); * ``` */ export declare class Edwards implements Readonly<SignatureCurve> { /** The underlying curve implementation */ readonly curve: CurveFn_2; /** Function to generate random bytes */ readonly randomBytes: RandomBytes; /** Curve identifier for Edwards */ readonly curveName: CurveName; /** Key byte length for Edwards */ readonly keyByteLength: number; /** Signature algorithm for Edwards */ signatureAlgorithmName: SignatureAlgorithmName; /** * Creates a new Edwards instance. * * @param {Object} params - Edwards constructor parameters * @param {CurveFn} params.curve - The curve implementation to use * @param {RandomBytes} params.randomBytes - Function to generate random bytes * @param {CurveName} params.curveName - Curve identifier (e.g. 'ed25519') * @param {SignatureAlgorithmName} params.signatureAlgorithmName - Signature algorithm name * @param {number} params.keyByteLength - Private/public key length in bytes */ constructor({ curve, randomBytes, curveName, signatureAlgorithmName, keyByteLength, }: EdwardsParams); /** * Gets the underlying curve implementation. * This method allows access to the raw CurveFn implementation when needed. * * @returns {CurveFn} The underlying curve implementation */ getCurve(): CurveFn_2; /** * Generates a random private key for Edwards. * The generated key is the length of the curve's order. * * @returns {Uint8Array} A random private key */ randomPrivateKey: () => Uint8Array; /** * Derives a public key from a private key. * * @param {Uint8Array} privateKey - The private key to derive from * @param {boolean} [compressed=true] - Whether the public key should be compressed * @returns {Uint8Array} The derived public key * @throws {Error} If the private key is invalid */ getPublicKey: (privateKey: Uint8Array, compressed?: boolean) => Uint8Array; /** * Signs a message using the Edwards curve and a private key. * * @param {SignParams} params - An object containing the message and private key. * @param {Uint8Array} params.message - The message to be signed as a Uint8Array. * @param {Uint8Array} params.privateKey - The private key as a Uint8Array. * @param {boolean} [params.recovered=false] - Whether to request a recoverable signature (not supported) * @returns {Uint8Array} The signature as a Uint8Array. */ sign: ({ message, privateKey, recovered, }: SignParams) => Uint8Array; /** * Verifies a signature using the Edwards curve and a public key. * * @param {VerifyParams} params - An object containing the signature, message, and public key. * @param {Uint8Array} params.signature - The signature to be verified as a Uint8Array. * @param {Uint8Array} params.message - The message that was signed as a Uint8Array. * @param {Uint8Array} params.publicKey - The public key as a Uint8Array. * @returns {boolean} True if the signature is valid, false otherwise. */ verify: ({ signature, message, publicKey }: VerifyParams) => boolean; /** * Attempts to recover a public key from a signature and message. * Note: Public key recovery is not supported for the Edwards curve. * * @param {RecoverPublicKeyParams} _params - The signature and message to attempt recovery from * @throws {Error} Always throws because public key recovery is not supported for Edwards */ recoverPublicKey: (_params: RecoverPublicKeyParams) => Uint8Array; /** * Converts a private key to JWK format. * * @param {Uint8Array} privateKey - The private key to convert * @returns {JwkPrivateKey} The private key in JWK format * @throws {Error} If the private key is invalid */ toJwkPrivateKey: (privateKey: Uint8Array) => JwkPrivateKey; /** * Converts a public key to JWK format. * * @param {Uint8Array} publicKey - The public key to convert * @returns {JwkPublicKey} The public key in JWK format * @throws {Error} If the public key is invalid */ toJwkPublicKey: (publicKey: Uint8Array) => JwkPublicKey; /** * Converts a JWK private key to raw format. * * @param {JwkPrivateKey} jwkPrivateKey - The JWK private key to convert * @returns {Uint8Array} The private key in raw format * @throws {Error} If the JWK is invalid */ toRawPrivateKey: (jwkPrivateKey: JwkPrivateKey) => Uint8Array; /** * Converts a JWK public key to raw format. * * @param {JwkPublicKey} jwkPublicKey - The JWK public key to convert * @returns {Uint8Array} The public key in raw format * @throws {Error} If the JWK is invalid */ toRawPublicKey: (jwkPublicKey: JwkPublicKey) => Uint8Array; } /** * A constant array containing the names of supported Edwards curves. * Currently, it includes only 'Ed25519'. */ export declare const EDWARDS_CURVE_NAMES: readonly ["Ed25519"]; /** * A type representing the name of an Edwards curve. * It is a union type of the values in EDWARDS_CURVE_NAMES. */ export declare type EdwardsCurveName = (typeof EDWARDS_CURVE_NAMES)[number]; /** * Derives a public key from a private key using the edwards curve. * Accepts either: * - a raw seed of length `keyByteLength`, or * - a concatenation of `seed || embeddedPublicKey` of length `keyByteLength * 2`. * * @param {CurveFn} curve - The curve function used to derive the public key. * @param {number} keyByteLength - The base key byte length (seed length, without embedded public key). * @param {Uint8Array} privateKey - Private key as Uint8Array of length `keyByteLength` or `keyByteLength * 2` (seed || embeddedPublicKey). * @param {boolean} [compressed=true] - Indicates if the public key should be compressed. * @returns {Uint8Array} The derived public key. * @throws {Error} Throws an error if `compressed` is false, if the embedded public key is invalid, or if derivation fails. */ export declare const edwardsGetPublicKey: (curve: CurveFn_2, keyByteLength: number, privateKey: Uint8Array, compressed?: boolean) => Uint8Array; /** * Twisted Edwards curve options. * * * a: formula param * * d: formula param * * p: prime characteristic (order) of finite field, in which arithmetics is done * * n: order of prime subgroup a.k.a total amount of valid curve points * * h: cofactor. h*n is group order; n is subgroup order * * Gx: x coordinate of generator point a.k.a. base point * * Gy: y coordinate of generator point */ export declare type EdwardsOpts = Readonly<{ a: bigint; d: bigint; p: bigint; n: bigint; h: bigint; Gx: bigint; Gy: bigint; }>; declare type EdwardsParams = { curve: CurveFn_2; randomBytes: RandomBytes; curveName: CurveName; signatureAlgorithmName: SignatureAlgorithmName; keyByteLength: number; }; /** * Generates a random private key for the edwards curve. * * @param {CurveFn} curve - The curve function used to generate the private key. * @returns {Uint8Array} A randomly generated private key as a Uint8Array. * @throws {Error} Throws an error if the private key generation fails. */ export declare const edwardsRandomPrivateKey: (curve: CurveFn_2) => Uint8Array; /** * Signs a message using the edwards curve and a private key. * * @param {CurveFn} curve - The curve function used for signing. * @param {number} keyByteLength - The byte length of the private key. * @param {SignParams} params - An object containing the message and private key. * @param {Uint8Array} params.message - The message to be signed as a Uint8Array. * @param {Uint8Array} params.privateKey - The private key as a Uint8Array. * @param {boolean} [params.recovered=false] - Indicates if the signature should be in recovered format. * @returns {Uint8Array} The signature as a Uint8Array. * @throws {Error} Throws an error if recovered signature is requested or if signing fails. */ export declare const edwardsSign: (curve: CurveFn_2, keyByteLength: number, { message, privateKey, recovered }: SignParams) => Uint8Array; /** * Converts an edwards private key to a JWK format. * * @param {CurveFn} curve - The curve function used to derive the public key. * @param {number} keyByteLength - The expected byte length of the key. * @param {Uint8Array} privateKey - The private key as a Uint8Array. * @returns {JwkPrivateKey} The private key in JWK format. * @throws {Error} Throws an error if the private key conversion fails. */ export declare const edwardsToJwkPrivateKey: (curve: CurveFn_2, keyByteLength: number, privateKey: Uint8Array) => JwkPrivateKey; /** * Converts an edwards public key to a JWK format. * * @param {CurveFn} _curve - The curve function (unused in current implementation). * @param {number} keyByteLength - The expected byte length of the public key. * @param {Uint8Array} publicKey - The public key as a Uint8Array. * @returns {JwkPublicKey} The public key in JWK format. * @throws {Error} Throws an error if the public key conversion fails. */ export declare const edwardsToJwkPublicKey: (_curve: CurveFn_2, keyByteLength: number, publicKey: Uint8Array) => JwkPublicKey; /** * Converts a JWK formatted edwards private key to a raw private key. * * @param {CurveFn} curve - The curve function used for conversion. * @param {number} keyByteLength - The expected byte length of the key. * @param {CurveName} curveName - The expected curve name for validation. * @param {JwkPrivateKey} jwkPrivateKey - The private key in JWK format. * @returns {Uint8Array} The private key as a raw Uint8Array. * @throws {Error} Throws an error if the JWK is invalid or if the decoding fails. */ export declare const edwardsToRawPrivateKey: (curve: CurveFn_2, keyByteLength: number, curveName: CurveName, jwkPrivateKey: JwkPrivateKey) => Uint8Array; /* Excluded from this release type: edwardsToRawPrivateKeyInternal */ /** * Converts a JWK formatted edwards public key to a raw public key. * * @param {CurveFn} curve - The curve function used for conversion. * @param {number} keyByteLength - The expected byte length of the public key. * @param {CurveName} curveName - The expected curve name for validation. * @param {JwkPublicKey} jwkPublicKey - The public key in JWK format. * @returns {Uint8Array} The public key as a raw Uint8Array. * @throws {Error} Throws an error if the JWK is invalid or if the conversion fails. */ export declare const edwardsToRawPublicKey: (curve: CurveFn_2, keyByteLength: number, curveName: CurveName, jwkPublicKey: JwkPublicKey) => Uint8Array; /* Excluded from this release type: edwardsToRawPublicKeyInternal */ /** * Verifies a signature using the edwards curve and a public key. * * @param {CurveFn} curve - The curve function used for verification. * @param {VerifyParams} params - An object containing the signature, message, and public key. * @param {Uint8Array} params.signature - The signature to be verified as a Uint8Array. * @param {Uint8Array} params.message - The message that was signed as a Uint8Array. * @param {Uint8Array} params.publicKey - The public key as a Uint8Array. * @returns {boolean} True if the signature is valid, false otherwise. */ export declare const edwardsVerify: (curve: CurveFn_2, { signature, message, publicKey }: VerifyParams) => boolean; /** * When Weierstrass curve has `a=0`, it becomes Koblitz curve. * Koblitz curves allow using **efficiently-computable GLV endomorphism ψ**. * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. * * Endomorphism consists of beta, lambda and splitScalar: * * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)` * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)` * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)` * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than * one 256-bit multiplication. * * where * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1 * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1 * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors. * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)` * * Check out `test/misc/endomorphism.js` and * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066). */ export declare type EndomorphismOpts = { beta: bigint; splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint; }; }; /** * Extracts the algorithm OID string from an ASN.1 block. * * @param block - The ASN.1 block containing the algorithm identifier. * @returns The algorithm OID string. */ export declare const extractAlgorithmOidString: (block: asn1js.BaseBlock) => string; /** * Extracts the private key from an EC ASN.1 block. * * @param block - The ASN.1 block containing the EC private key. * @returns The extracted private key as an ArrayBuffer. * @throws Will throw an error if the ASN.1 structure is invalid for an EC private key. */ export declare const extractEcPrivateKey: (block: asn1js.BaseBlock) => ArrayBuffer; /** * Extracts the value of an OCTET STRING from an ASN.1 block. * * @param block - The ASN.1 block containing the OCTET STRING. * @returns The extracted OCTET STRING value. */ export declare const extractOctetString: (block: asn1js.BaseBlock) => ArrayBuffer; /** * Extracts the private key from an OKP ASN.1 block. * * @param block - The ASN.1 block containing the OKP private key. * @returns The extracted private key as an ArrayBuffer. */ export declare const extractOkpPrivateKey: (block: asn1js.BaseBlock) => ArrayBuffer; /** * Extracts the raw private key from a PKCS#8 encoded ArrayBuffer. * * @param pkcs8Array - The PKCS#8 encoded private key. * @returns The raw private key as an ArrayBuffer. */ export declare const extractRawPrivateKeyFromPkcs8: (pkcs8Array: ArrayBuffer) => ArrayBuffer; /** * Converts a raw signature into a SignatureType using the specified Weierstrass curve. * * @param {CurveFn} curve - The curve function used for signature conversion. * @param {Uint8Array} rawSignature - The raw signature as a Uint8Array. * @returns {SignatureType} The converted signature as a RecoveredSignatureType. * @throws {Error} Throws an error if the raw signature length is invalid. */ export declare const fromRawSignature: (curve: CurveFn_3, rawSignature: Uint8Array) => SignatureType; /** * Extracts the error message from an unknown error object. * * @param {unknown} error - The error object from which to extract the message. * @returns {string} The extracted error message, or a string representation of the error if it's not an instance of Error. */ export declare const getErrorMessage: (error: unknown) => string; /** * Retrieves the public key from a private key. * @typedef {Function} GetPublicKey * @param {Uint8Array} privateKey - The private key as a Uint8Array * @param {boolean} [compressed] - Whether the public key should be compressed * @returns {Uint8Array} The public key as a Uint8Array */ export declare type GetPublicKey = (privateKey: Uint8Array, compressed?: boolean) => Uint8Array; /** * Generates a shared secret from a private and public key. * @typedef {Function} GetSharedSecret * @param {GetSharedSecretParams} params - Parameters containing private and public keys * @returns {Uint8Array} The shared secret as a Uint8Array */ export declare type GetSharedSecret = ({ privateKey, publicKey, }: GetSharedSecretParams) => Uint8Array; /** * Parameters for generating a shared secret. * @typedef {Object} GetSharedSecretParams@typedef {Object} GetSharedSecretParams * @property {Uint8Array} privateKey - The private key as a Uint8Array * @property {Uint8Array} publicKey - The public key as a Uint8Array */ export declare type GetSharedSecretParams = { privateKey: Uint8Array; publicKey: Uint8Array; }; declare type Hex = string | Uint8Array; export declare function inRange(n: bigint, min: bigint, max: bigint): boolean; /** * Checks if the given OID string corresponds to an OKP (Octet Key Pair). * * @param oidString - The OID string to check. * @returns True if the OID string is for an OKP, false otherwise. */ export declare const isOkp: (oidString: string) => boolean; /** * Base JSON Web Key (JWK) structure containing common properties. * @typedef {Object} JwkBase@typedef {Object} JwkBase * @property {string} kty - Key type * @property {string} crv - Curve name * @property {string} [alg] - Algorithm * @property {string} x - X coordinate in base64url format * @property {string} [y] - Y coordinate in base64url format * @property {string[]} [key_ops] - Key operations */ export declare type JwkBase = { kty: string; crv?: string; alg?: string; x: string; y?: string; key_ops?: string[]; }; /** * JSON Web Key (JWK) representation of a private key. * Extends JwkBase with a private key component. * @typedef {Object} JwkPrivateKey@typedef {Object} JwkPrivateKey * @property {string} d - Private key in base64url format */ export declare type JwkPrivateKey = JwkBase & { d: string; }; /** * JSON Web Key (JWK) representation of a public key. * Extends JwkBase with an optional key identifier. * @typedef {Object} JwkPublicKey@typedef {Object} JwkPublicKey * @property {string} [kid] - Key identifier */ export declare type JwkPublicKey = JwkBase & { kid?: string; }; /** * Montgomery implementation for Elliptic Curve Diffie-Hellman (ECDH) key exchange. * This class provides a high-level interface for Montgomery operations, including * key generation, validation, and shared secret computation. * * @example * ```typescript * const montgomery = new Montgomery({ * curve, * randomBytes, * curveName: 'X25519', * keyByteLength: 32, * }); * const privateKey = montgomery.randomPrivateKey(); * const publicKey = montgomery.getPublicKey(privateKey); * const peerPublicKey = ...; // Uint8Array from peer * const sharedSecret = montgomery.getSharedSecret({ privateKey, publicKey: peerPublicKey }); * ``` */ export declare class Montgomery implements Readonly<EcdhCurve> { /** The underlying curve implementation */ readonly curve: CurveFn_4; /** Function to generate random bytes */ readonly randomBytes: RandomBytes; /** Curve identifier for Montgomery */ readonly curveName: CurveName; /** Key byte length for Montgomery */ readonly keyByteLength: number; /** * Creates a new Montgomery instance. * * @param {object} params - Constructor parameters * @param {CurveFn} params.curve - The curve implementation to use * @param {RandomBytes} params.randomBytes - Function to generate random bytes * @param {CurveName} params.curveName - Curve name identifier (e.g. 'X25519') * @param {number} params.keyByteLength - Expected byte length of keys (e.g. 32 for X25519) */ constructor({ curve, randomBytes, curveName, keyByteLength, }: MontgomeryParams); /** * Gets the underlying curve implementation. * This method allows access to the raw CurveFn implementation when needed. * * @returns {CurveFn} The underlying curve implementation */ getCurve(): CurveFn_4; /** * Generates a random private key for the Montgomery curve. * * @returns {Uint8Array} The random private key */ randomPrivateKey(): Uint8Array; /** * Derives a public key from a private key. * * @param {Uint8Array} privateKey - The private key to derive from * @param {boolean} [compressed=true] - Whether to return a compressed public key * @returns {Uint8Array} The derived public key * @throws {Error} If the private key is invalid or uncompressed keys are requested */ getPublicKey(privateKey: Uint8Array, compressed?: boolean): Uint8Array; /** * Computes a shared secret using ECDH. * * @param {GetSharedSecretParams} params - The parameters for shared secret computation * @param {Uint8Array} params.privateKey - The private key * @param {Uint8Array} params.publicKey - The public key * @returns {Uint8Array} The computed shared secret * @throws {Error} If either the private key or public key is invalid */ getSharedSecret({ privateKey, publicKey, }: GetSharedSecretParams): Uint8Array; /** * Converts a private key to JWK format. * * @param {Uint8Array} privateKey - The private key to convert * @returns {JwkPrivateKey} The private key in JWK format * @throws {Error} If the private key is invalid */ toJwkPrivateKey(privateKey: Uint8Array): JwkPrivateKey; /** * Converts a public key to JWK format. * * @param {Uint8Array} publicKey - The public key to convert * @returns {JwkPublicKey} The public key in JWK format * @throws {Error} If the public key is invalid */ toJwkPublicKey(publicKey: Uint8Array): JwkPublicKey; /** * Converts a JWK private key to raw format. * * @param {JwkPrivateKey} jwkPrivateKey - The JWK private key to convert * @returns {Uint8Array} The private key in raw format * @throws {Error} If the JWK is invalid */ toRawPrivateKey(jwkPrivateKey: JwkPrivateKey): Uint8Array; /** * Converts a JWK public key to raw format. * * @param {JwkPublicKey} jwkPublicKey - The JWK public key to convert * @returns {Uint8Array} The public key in raw format * @throws {Error} If the JWK is invalid */ toRawPublicKey(jwkPublicKey: JwkPublicKey): Uint8Array; } export declare function montgomery(curveDef: CurveType): CurveFn; /** * A constant array containing the names of supported Montgomery curves. * Currently, it includes only 'X25519'. */ export declare const MONTGOMERY_CURVE_NAMES: readonly ["X25519"]; /** * A type representing the name of an Montgomery curve. * It is a union type of the values in MONTGOMERY_CURVE_NAMES. */ export declare type MontgomeryCurveName = (typeof MONTGOMERY_CURVE_NAMES)[number]; /** * Generates a public key for the Montgomery curve from a given private key. * * @param {CurveFn} curve - The curve function used to generate the public key. * @param {Uint8Array} privateKey - The private key as a Uint8Array. * @param {boolean} [compressed=true] - Indicates if the public key should be compressed. * Note: x25519 only supports compressed public keys. * @returns {Uint8Array} The generated public key as a Uint8Array. * @throws {Error} Throws an error if uncompressed public keys are requested or if the private key is invalid. */ export declare const montgomeryGetPublicKey: (curve: CurveFn_4, privateKey: Uint8Array, compressed?: boolean) => Uint8Array; /** * Computes the shared secret for the Montgomery curve using a private key and a public key. * * @param {CurveFn} curve - The curve function used to compute the shared secret. * @param {CurveName} curveName - The name of the curve to validate against. * @param {GetSharedSecretParams} params - An object containing the private and public keys. * @param {Uint8Array} params.privateKey - The private key as a Uint8Array. * @param {Uint8Array} params.publicKey - The public key as a Uint8Array. * @returns {Uint8Array} The computed shared secret as a Uint8Array. * @throws {Error} Throws an error if the private key or public key is invalid. */ export declare const montgomeryGetSharedSecret: (curve: CurveFn_4, curveName: CurveName, { privateKey, publicKey }: GetSharedSecretParams) => Uint8Array; declare type MontgomeryParams = { curve: CurveFn_4; randomBytes: RandomBytes; curveName: CurveName; keyByteLength: number; }; /** * Generates a random private key for the Montgomery curve. * * This function utilizes the curve's utility method to generate a random private key. * * @param {CurveFn} curve - The curve function used to generate the private key. * @returns {Uint8Array} A randomly generated private key. * @throws {Error} Throws an error if the random private key generation fails. */ export declare const montgomeryRandomPrivateKey: (curve: CurveFn_4) => Uint8Array; /** * Converts a raw Montgomery private key to JWK format. * * @param {CurveFn} curve - The curve function used for conversion. * @param {number} keyByteLength - The expected byte length of the public key. * @param {CurveName} curveName - The curve name for the JWK. * @param {Uint8Array} privateKey - The private key in raw format. * @returns {JwkPrivateKey} The private key in JWK format. * @throws {Error} Throws an error if the conversion fails. */ export declare const montgomeryToJwkPrivateKey: (curve: CurveFn_4, keyByteLength: number, curveName: CurveName, privateKey: Uint8Array) => JwkPrivateKey; /** * Converts a raw Montgomery public key to JWK format. * * @param {CurveFn} _curve - The curve function (unused in this implementation). * @param {number} keyByteLength - The expected byte length of the public key. * @param {CurveName} curveName - The curve name for the JWK. * @param {Uint8Array} publicKey - The public key in raw format. * @returns {JwkPublicKey} The public key in JWK format. * @throws {Error} Throws an error if the conversion fails. */ export declare const montgomeryToJwkPublicKey: (_curve: CurveFn_4, keyByteLength: number, curveName: CurveName, publicKey: Uint8Array) => JwkPublicKey; /** * Converts a JWK formatted Montgomery private key to a raw private key. * * @param {CurveFn} curve - The curve function used for conversion. * @param {number} keyByteLength - The expected byte length of the key. * @param {CurveName} curveName - The name of the curve to validate against. * @param {JwkPrivateKey} jwkPrivateKey - The private key in JWK format. * @returns {Uint8Array} The private key as a raw Uint8Array. * @throws {Error} Throws an error if the JWK is invalid or if the conversion fails. */ export declare const montgomeryToRawPrivateKey: (curve: CurveFn_4, keyByteLength: number, curveName: CurveName, jwkPrivateKey: JwkPrivateKey) => Uint8Array; /* Excluded from this release type: montgomeryToRawPrivateKeyInternal */ /** * Converts a JWK formatted Montgomery public key to a raw public key. * * @param {CurveFn} curve - The curve function used for conversion. * @param {number} keyByteLength - The expected byte length of the key. * @param {CurveName} curveName - The name of the curve to validate against. * @param {JwkPublicKey} jwkPublicKey - The public key in JWK format. * @returns {Uint8Array} The public key as a raw Uint8Array. * @throws {Error} Throws an error if the JWK is invalid or if the conversion fails. */ export declare const montgomeryToRawPublicKey: (curve: CurveFn_4, keyByteLength: number, curveName: CurveName, jwkPublicKey: JwkPublicKey) => Uint8Array; /** * Converts a JWK formatted Montgomery public key to a raw public key. * * @param {CurveFn} _curve - The curve function (unused in this implementation). * @param {number} keyByteLength - The expected byte length of the key. * @param {CurveName} curveName - The name of the curve to validate against. * @param {JwkPublicKey} jwkPublicKey - The public key in JWK format. * @returns {Uint8Array} The public key as a raw Uint8Array. * @throws {Error} Throws an error if the JWK is invalid or if the decoding fails. */ export declare const montgomeryToRawPublicKeyInternal: (_curve: CurveFn_4, keyByteLength: number, curveName: CurveName, jwkPublicKey: JwkPublicKey) => Uint8Array; export declare const p256_CURVE: WeierstrassOpts<bigint>; export declare const p384_CURVE: WeierstrassOpts<bigint>; export declare const p521_CURVE: WeierstrassOpts<bigint>; /** * Parses a DER encoded ArrayBuffer into an ASN.1 Sequence. * * @param derArray - The DER encoded data. * @returns The parsed ASN.1 sequence. */ export declare const parseDER: (derArray: ArrayBuffer) => asn1js.Sequence; /** * Function type that generates random bytes. * @param byteLength - Optional number of bytes to generate. If not provided, implementation should choose appropriate length. * @returns Uint8Array containing the generated random bytes. */ export declare type RandomBytes = (byteLength?: number) => Uint8Array; /** * Generates a random private key. * @typedef {Function} RandomPrivateKey * @returns {Uint8Array} A random private key as a Uint8Array */ export declare type RandomPrivateKey = () => Uint8Array; /** * Recovers a public key from a signature and message. * @typedef {Function} RecoverPublicKey * @param {RecoverPublicKeyParams} params - Parameters containing the signature, message, and compression option * @returns {Uint8Array} The recovered public key as a Uint8Array */ export declare type RecoverPublicKey = ({ signature, message, compressed, }: RecoverPublicKeyParams) => Uint8Array; /** * Parameters for recovering a public key from a signature. * @typedef {Object} RecoverPublicKeyParams@typedef {Object} RecoverPublicKeyParams * @property {Uint8Array} signature - The signature used for recovery as a Uint8Array * @property {Uint8Array} message - The message that was signed as a Uint8Array * @property {boolean} [compressed] - Whether the recovered public key should be compressed */ export declare type RecoverPublicKeyParams = { signature: Uint8Array; message: Uint8Array; compressed?: boolean; }; /** * Resolves the algorithm name from JWK fields. * It first checks if the algorithmName is provided. If both algorithmName and curveName are * provided, it validates that they are consistent (the algorithm name derived from the curve must * match the provided algorithm name). If algorithmName is not provided, it attempts to derive the * algorithm name from the curveName using the internal mapping. If neither is available or the * curve is not supported, it throws an error. * @typedef {Function} ResolveAlgorithmName * @param {ResolveAlgorithmNameParams} params - Parameters containing algorithmName and/or curveName * @returns {string} The resolved algorithm name * @throws {Error} Throws an error if: * - Neither algorithmName nor curveName is provided * - algorithmName and curveName are provided but do not match * - algorithmName is not provided and curveName cannot be resolved to an algorithm name */ export declare const resolveAlgorithmName: ({ algorithmName, curveName, }: ResolveAlgorithmNameParams) => string; /** * Parameters for resolving algorithm name from JWK fields. * * @typedef {ResolveAlgorithmNameParams} * @property {string} [algorithmName] - The `alg` field from a JWK (may be undefined). * @property {string} [curveName] - The `crv` field from a JWK (may be undefined). */ export declare type ResolveAlgorithmNameParams = { /** The `alg` field from a JWK (may be undefined). */ algorithmName?: string; /** The `crv` field from a JWK (may be undefined). */ curveName?: string; }; /** * Resolves a curve name from either a curve name or an algorithm name. * If both are provided, validates that they are consistent. * If only algorithmName is provided, derives the curve name from it. * If only curveName is provided, returns it as-is. * @typedef {Function} ResolveCurveName * @param {ResolveCurveNameParams} params - Parameters containing curveName and/or algorithmName * @returns {string} The resolved curve name * @throws {Error} Throws an error if: * - Neither curveName nor algorithmName is provided * - curveName and algorithmName are provided but do not match * - algorithmName is provided but cannot be resolved to a curve name */ export declare const resolveCurveName: ({ curveName, algorithmName, }: ResolveCurveNameParams) => string; /** * Parameters for resolving a curve name. * @typedef {Object} ResolveCurveNameParams@typedef {Object} ResolveCurveNameParams * @property {string} [curveName] - The curve name (e.g., 'P-256', 'secp256k1') * @property {string} [algorithmName] - The algorithm name (e.g., 'ES256', 'ES384') */ declare interface ResolveCurveNameParams { curveName?: string; algorithmName?: string; } export declare const secp256k1_CURVE: WeierstrassOpts<bigint>; /** * Signs a message with a private key. * @typedef {Function} Sign * @param {SignParams} params - Parameters containing the private key and message * @returns {Uint8Array} The signature as a Uint8Array */ export declare type Sign = ({ privateKey, message }: SignParams) => Uint8Array; /** * Represents the names of supported signature algorithms. * @typedef {('ES256' | 'ES384' | 'ES512' | 'ES256K' | 'EdDSA')} SignatureAlgorithmName */ export declare type SignatureAlgorithmName = 'ES256' | 'ES384' | 'ES512' | 'ES256K' | 'EdDSA'; /** * Interface for signature operations. * Extends UnifiedBase with methods to sign and verify messages. * @interface Signature * @extends UnifiedBase * @property {SignatureAlgorithmName} signatureAlgorithmName - Signature algorithm name * @property {Sign} sign - Function to sign a message * @property {Verify} verify - Function to verify a signature * @property {RecoverPublicKey} recoverPublicKey - Function to recover a public key from a signature and message */ export declare interface SignatureCurve extends UnifiedBase { signatureAlgorithmName: SignatureAlgorithmName; sign: Sign; verify: Verify; recoverPublicKey: RecoverPublicKey; } /** * Represents the names of curves used for signature operations. * Excludes 'X25519' as it is not used for signatures. * @typedef {Exclude<CurveName, 'X25519'>} SignatureCurveName */ export declare type SignatureCurveName = Exclude<CurveName, 'X25519'>; /** * Represents a signature-like object containing r and s values. * Used for elliptic curve digital signatures. */ export declare type SignatureLike = { r: bigint; s: bigint; }; /** * Parameters for signing a message. * @typedef {Object} SignParams@typedef {Object} SignParams * @property {Uint8Array} privateKey - The private key as a Uint8Array * @property {Uint8Array} message - The message to sign as a Uint8Array * @property {boolean} [recovered] - Optional. Indicates if the signature should be in recovered format. */ export declare type SignParams = { privateKey: Uint8Array; message: Uint8Array; recovered?: boolean; }; export declare const SMALL_ORDER_POINTS: Uint8Array<ArrayBufferLike>[]; /** * Converts a private key to a JWK object. * @typedef {Function} ToJwkPrivateKey * @param {Uint8Array} privateKey - The private key as a Uint8Array * @returns {JwkPrivateKey} JWK representation of the private key */ export declare type ToJwkPrivateKey = (privateKey: Uint8Array) => JwkPrivateKey; /** * Converts a public key to a JWK object. * @typedef {Function} ToJwkPublicKey * @param {Uint8Array} publicKey - The public key as a Uint8Array * @returns {JwkPublicKey} JWK representation of the public key */ export declare type ToJwkPublicKey = (publicKey: Uint8Array) => JwkPublicKey; /** * Converts a JWK private key to raw private key format. * @typedef {Function} ToRawPrivateKey * @param {JwkPrivateKey} privateKey - The JWK private key containing x,y,d coordinates in base64url format * @returns {Uint8Array} Uint8Array containing the raw private key */ export declare type ToRawPrivateKey = (privateKey: JwkPrivateKey) => Uint8Array; /** * Converts a JWK public key to raw uncompressed public key format. * The resulting format is: 0x04 || x || y where x and y are coordinates. * @typedef {Function} ToRawPublicKey * @param {JwkPublicKey} publicKey - The JWK public key containing x and y coordinates in base64url format * @returns {Uint8Array} Uint8Array containing the raw uncompressed public key */ export declare type ToRawPublicKey = (publicKey: JwkPublicKey) => Uint8Array; /** * Converts a RecoveredSignatureType into a raw signature format. * * @param {RecoveredSignatureType} signature - The signature to convert. * @returns {Uint8Array} The raw signature as a Uint8Array, including the recovery byte. */ export declare const toRawRecoveredSignature: (signature: RecoveredSignatureType) => Uint8Array; /** * Base interface for unified cryptographic operations. * @interface UnifiedBase * @property {CurveName} curveName - Curve name * @property {number} keyByteLength - Key byte length * @property {RandomPrivateKey} randomPrivateKey - Function to generate a random private key * @property {GetPublicKey} getPublicKey - Function to retrieve the public key from a private key * @property {RandomBytes} randomBytes - Function to generate random bytes * @property {ToJwkPrivateKey} toJwkPrivateKey - Function to convert a private key to JWK format * @property {ToJwkPublicKey} toJwkPublicKey - Function to convert a public key to JWK format * @property {ToRawPrivateKey} toRawPrivateKey - Function to convert a JWK private key to raw format * @property {ToRawPublicKey} toRawPublicKey - Function to convert a JWK public key to raw format * @property {IsValidPublicKey} isValidPublicKey - Function to validate a public key * @property {IsValidPrivateKey} isValidPrivateKey - Function to validate a private key */ export declare interface UnifiedBase { curveName: CurveName; keyByteLength: number; randomPrivateKey: RandomPrivateKey; getPublicKey: GetPu