From f936507a8c3c3864edee39ffc0a6e041d7df1135 Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Tue, 16 Jan 2024 17:51:56 -0700 Subject: [PATCH] ecdsa: reduce `z` mod `q` when performing RFC6979 The RFC specifies this, however we were not performing it. Going forward, it would be nice to be able to refactor these APIs to operate over a `Scalar` which we know is always reduced. --- ecdsa/src/hazmat.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/ecdsa/src/hazmat.rs b/ecdsa/src/hazmat.rs index db14fac3..013dde9a 100644 --- a/ecdsa/src/hazmat.rs +++ b/ecdsa/src/hazmat.rs @@ -86,7 +86,7 @@ where /// described in [RFC6979] for computing ECDSA ephemeral scalar `k`. /// /// Accepts the following parameters: - /// - `z`: message digest to be signed. + /// - `z`: message digest to be signed, i.e. `H(m)`. Does not have to be reduced in advance. /// - `ad`: optional additional data, e.g. added entropy from an RNG /// /// [RFC6979]: https://datatracker.ietf.org/doc/html/rfc6979 @@ -100,10 +100,18 @@ where Self: From> + Invert>, D: Digest + BlockSizeUser + FixedOutput + FixedOutputReset, { + // From RFC6979 ยง 2.4: + // + // H(m) is transformed into an integer modulo q using the bits2int + // transform and an extra modular reduction: + // + // h = bits2int(H(m)) mod q + let z2 = as Reduce>::reduce_bytes(z); + let k = Scalar::::from_repr(rfc6979::generate_k::( &self.to_repr(), &C::ORDER.encode_field_bytes(), - z, + &z2.to_repr(), ad, )) .unwrap();