From: Chris Duncan Date: Wed, 15 Apr 2026 08:35:01 +0000 (-0700) Subject: Extract byte handling of inputs to Tools functions and encode string inputs as bytes... X-Git-Tag: v0.12.0~4^2~7 X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=9ae3eb2f7f646684522a06ff41af18d2db81ab7d;p=libnemo.git Extract byte handling of inputs to Tools functions and encode string inputs as bytes prior to signing or verifying. --- diff --git a/src/lib/tools.ts b/src/lib/tools.ts index 9c0db6f..b8137af 100644 --- a/src/lib/tools.ts +++ b/src/lib/tools.ts @@ -17,6 +17,14 @@ type SweepResult = { } export class Tools { + static #encoder: TextEncoder = new TextEncoder() + static #normalize (input: string | ArrayBuffer | Uint8Array): Uint8Array { + return (typeof input === 'string') + ? hex.toBytes(input) + : input instanceof ArrayBuffer + ? new Uint8Array(input.slice()) + : input + } /** * Converts a decimal amount of nano from one unit divider to another. * @@ -134,16 +142,19 @@ export class Tools { * Concatenates and signs an arbitrary set of strings with a secret key using * nano25519. The input data can be up to 32 KiB in total. * - * @param {string} secretKey - 64-byte hexadecimal secret key + * @param {(string | ArrayBuffer | Uint8Array)} secretKey - 64-byte secret key * @param {...string[]} input - Data to be concatenated and then signed * @returns {string} 64-byte hexadecimal signature */ - static sign (secretKey: string, ...input: string[]): string { + static sign (secretKey: string | ArrayBuffer | Uint8Array, ...input: string[]): string { + const k = this.#normalize(secretKey) try { - const signature = nano25519_sign(input.join(''), secretKey) - return signature + const signature = nano25519_sign(this.#encoder.encode(input.join('')), k) + return bytes.toHex(signature) } catch (err) { throw new Error(`Failed to sign message`, { cause: err }) + } finally { + k.fill(0) } } @@ -208,14 +219,16 @@ export class Tools { /** * Verifies the signature of arbitrary strings using a public key. * - * @param {string} publicKey - 64-character hexadecimal public key - * @param {string} signature - 128-character hexadcimal signature + * @param {(string | ArrayBuffer | Uint8Array)} publicKey - 32-byte hexadecimal public key + * @param {(string | ArrayBuffer | Uint8Array)} signature - 128-character hexadcimal signature * @param {...string} input - Data to be verified * @returns {boolean} True if the data was signed by the public key's matching private key */ - static verify (publicKey: string, signature: string, ...input: string[]): boolean { + static verify (publicKey: string | ArrayBuffer | Uint8Array, signature: string | ArrayBuffer | Uint8Array, ...input: string[]): boolean { + const k = this.#normalize(publicKey) + const s = this.#normalize(signature) try { - return nano25519_verify(signature, input.join(''), publicKey) + return nano25519_verify(s, this.#encoder.encode(input.join('')), k) } catch (err) { throw new Error('Failed to verify signature', { cause: err }) }