From 05794c0283650081aa2d193bf25771c2040d97aa Mon Sep 17 00:00:00 2001 From: Paul Miller Date: Fri, 11 Aug 2023 10:22:37 +0000 Subject: [PATCH] weierstrass, bls: improve randomPrivateKey security and decrease bias --- src/abstract/bls.ts | 5 ++++- src/abstract/weierstrass.ts | 10 ++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/abstract/bls.ts b/src/abstract/bls.ts index 7e965b2..282cbe7 100644 --- a/src/abstract/bls.ts +++ b/src/abstract/bls.ts @@ -189,7 +189,10 @@ export function bls( const utils = { randomPrivateKey: (): Uint8Array => { - return Fr.toBytes(hashToPrivateScalar(CURVE.randomBytes(groupLen + 8), CURVE.params.r)); + const bytesTaken = groupLen + Math.ceil(groupLen / 2); // e.g. 48b for 32b field + const rand = CURVE.randomBytes(bytesTaken); + const num = hashToPrivateScalar(rand, Fr.ORDER); + return Fr.toBytes(num); }, calcPairingPrecomputes, }; diff --git a/src/abstract/weierstrass.ts b/src/abstract/weierstrass.ts index 22fef3f..efa2fd0 100644 --- a/src/abstract/weierstrass.ts +++ b/src/abstract/weierstrass.ts @@ -845,13 +845,15 @@ export function weierstrass(curveDef: CurveType): CurveFn { normPrivateKeyToScalar: normPrivateKeyToScalar, /** - * Produces cryptographically secure private key from random of size (nBitLength+64) - * as per FIPS 186 B.4.1 with modulo bias being neglible. + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. */ randomPrivateKey: (): Uint8Array => { - const rand = CURVE.randomBytes(Fp.BYTES + 8); + const groupLen = CURVE.nByteLength; + const bytesTaken = groupLen + Math.ceil(groupLen / 2); // e.g. 48b for 32b field + const rand = CURVE.randomBytes(bytesTaken); const num = mod.hashToPrivateScalar(rand, CURVE_ORDER); - return ut.numberToBytesBE(num, CURVE.nByteLength); + return ut.numberToBytesBE(num, groupLen); }, /**