From: Chris Duncan Date: Fri, 5 Dec 2025 14:49:03 +0000 (-0800) Subject: Avoid string conversion when casting bigint to 32-byte buffer. X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=cbc35b58ce65e32eed6cb22496bd7673db0a760a;p=libnemo.git Avoid string conversion when casting bigint to 32-byte buffer. --- diff --git a/src/lib/crypto/secp256k1.ts b/src/lib/crypto/secp256k1.ts index 9857760..9c95e4d 100644 --- a/src/lib/crypto/secp256k1.ts +++ b/src/lib/crypto/secp256k1.ts @@ -310,11 +310,13 @@ export class Secp256k1 { /** Number to 32b. Must be 0 <= num < 2²⁵⁶. validate, pad, to bytes. */ static bigintTo32Bytes (num: bigint): Bytes { - return this.hexToBytes(this - .bigintInRange(num, 0n, 2n ** 256n) // secp256k1 is weierstrass curve. Equation is x³ + ax + b. - .toString(16) - .padStart(this.L2, '0') - ) + this.bigintInRange(num, 0n, 2n ** 256n) // secp256k1 is weierstrass curve. Equation is x³ + ax + b. + let len = this.L, bytes = new Uint8Array(len) + for (let i = len - 1; i >= 0; i--) { + bytes[i] = Number(num & 0xffn) + num >>= 8n + } + return bytes } /** Normalize private key to scalar (bigint). Verifies scalar is in range 1