From 9f7df0f13bd3e50425429c2e7cde11defda050e7 Mon Sep 17 00:00:00 2001 From: Paul Miller Date: Sun, 8 Jan 2023 17:46:55 +0000 Subject: [PATCH] ECDSA adjustments --- src/abstract/weierstrass.ts | 23 +++++++++++++++++------ test/basic.test.js | 7 ++++++- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/src/abstract/weierstrass.ts b/src/abstract/weierstrass.ts index 27cf50c..4fdfb59 100644 --- a/src/abstract/weierstrass.ts +++ b/src/abstract/weierstrass.ts @@ -922,16 +922,16 @@ export function weierstrass(curveDef: CurveType): CurveFn { function bits2int_2(bytes: Uint8Array): bigint { const delta = bytes.length * 8 - CURVE.nBitLength; - const big = bytesToNumberBE(bytes); - return delta > 0 ? big >> BigInt(delta) : big; + const num = bytesToNumberBE(bytes); + return delta > 0 ? num >> BigInt(delta) : num; } // Ensures ECDSA message hashes are 32 bytes and < curve order function _truncateHash(hash: Uint8Array, truncateOnly = false): bigint { - let h = bits2int_2(hash); + const h = bits2int_2(hash); + if (truncateOnly) return h; const { n } = CURVE; - if (!truncateOnly && h >= n) h -= n; - return h; + return h >= n ? h - n : h; } const truncateHash = CURVE.truncateHash || _truncateHash; @@ -1134,8 +1134,19 @@ export function weierstrass(curveDef: CurveType): CurveFn { // RFC6979 methods function bits2int(bytes: Uint8Array): bigint { const { nByteLength } = CURVE; + if (!(bytes instanceof Uint8Array)) throw new Error('Expected Uint8Array'); const slice = bytes.length > nByteLength ? bytes.slice(0, nByteLength) : bytes; - return bytesToNumberBE(slice); + // const slice = bytes; nByteLength; nBitLength; + let num = bytesToNumberBE(slice); + // const { nBitLength } = CURVE; + // const delta = (bytes.length * 8) - nBitLength; + // if (delta > 0) { + // // console.log('bits=', bytes.length*8, 'CURVE n=', nBitLength, 'delta=', delta); + // // console.log(bytes.length, nBitLength, delta); + // // console.log(bytes, new Error().stack); + // num >>= BigInt(delta); + // } + return num; } function bits2octets(bytes: Uint8Array): Uint8Array { const z1 = bits2int(bytes); diff --git a/test/basic.test.js b/test/basic.test.js index c653fb1..636e5db 100644 --- a/test/basic.test.js +++ b/test/basic.test.js @@ -2,6 +2,7 @@ import { deepStrictEqual, throws } from 'assert'; import { should } from 'micro-should'; import * as fc from 'fast-check'; import * as mod from '../lib/esm/abstract/modular.js'; +import { bytesToHex as toHex } from '../lib/esm/abstract/utils.js'; // Generic tests for all curves in package import { secp192r1 } from '../lib/esm/p192.js'; import { secp224r1 } from '../lib/esm/p224.js'; @@ -497,7 +498,11 @@ for (const name in CURVES) { const priv = C.utils.randomPrivateKey(); const pub = C.getPublicKey(priv); const sig = C.sign(msg, priv); - deepStrictEqual(C.verify(sig, msg, pub), true); + deepStrictEqual( + C.verify(sig, msg, pub), + true, + `priv=${toHex(priv)},pub=${toHex(pub)},msg=${msg}` + ); }), { numRuns: NUM_RUNS } )