From 6ac6668b297654b7a3199a7417b20531dfd9d502 Mon Sep 17 00:00:00 2001 From: Jeffrey Walton Date: Sun, 25 Jun 2023 02:48:20 -0400 Subject: [PATCH] Remove unneeded check in Integer::Randomize(bitCount) (GH #1206) Update docs to specify case when bitCount==0 Add tests for Randomize function in debug builds --- integer.cpp | 8 ++++++-- integer.h | 1 + validat2.cpp | 42 +++++++++++++++++++++++++++++++++++++++++- 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/integer.cpp b/integer.cpp index 81e37b087..5d9043f0f 100644 --- a/integer.cpp +++ b/integer.cpp @@ -3522,8 +3522,12 @@ void Integer::Randomize(RandomNumberGenerator &rng, size_t nbits) const size_t nbytes = nbits/8 + 1; SecByteBlock buf(nbytes); rng.GenerateBlock(buf, nbytes); - if (nbytes) - buf[0] = (byte)Crop(buf[0], nbits % 8); + + // https://github.com/weidai11/cryptopp/issues/1206 + // if (nbytes) + // buf[0] = (byte)Crop(buf[0], nbits % 8); + + buf[0] = (byte)Crop(buf[0], nbits % 8); Decode(buf, nbytes, UNSIGNED); } diff --git a/integer.h b/integer.h index 4db6b9c37..541cee1c4 100644 --- a/integer.h +++ b/integer.h @@ -444,6 +444,7 @@ class CRYPTOPP_DLL Integer : private InitializeInteger, public ASN1Object /// \param rng RandomNumberGenerator used to generate material /// \param bitCount the number of bits in the resulting integer /// \details The random integer created is uniformly distributed over [0, 2bitCount]. + /// \note If \p bitCount is 0, then this Integer is set to 0 (and not 0 or 1). void Randomize(RandomNumberGenerator &rng, size_t bitCount); /// \brief Set this Integer to random integer diff --git a/validat2.cpp b/validat2.cpp index 5a3be458e..14089fffa 100644 --- a/validat2.cpp +++ b/validat2.cpp @@ -1280,7 +1280,47 @@ bool TestIntegerOps() std::cout << "FAILED:"; std::cout << " Exponentiation operations\n"; - return pass; + // ****************************** Integer Randomize ****************************** + + try + { + const word32 bitCounts[] = { + 0,1,2,3,4,5,6,7,8,9,15,16,17,31,32,33,63,64,65,127,128,129 + }; + + for (size_t i=0; i