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
This commit is contained in:
Jeffrey Walton 2023-06-25 02:48:20 -04:00
parent 3f36b1dd87
commit 6ac6668b29
No known key found for this signature in database
GPG Key ID: B36AB348921B1838
3 changed files with 48 additions and 3 deletions

View File

@ -3522,7 +3522,11 @@ void Integer::Randomize(RandomNumberGenerator &rng, size_t nbits)
const size_t nbytes = nbits/8 + 1;
SecByteBlock buf(nbytes);
rng.GenerateBlock(buf, nbytes);
if (nbytes)
// 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);
}

View File

@ -444,6 +444,7 @@ public:
/// \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 <tt>[0, 2<sup>bitCount</sup>]</tt>.
/// \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

View File

@ -1280,6 +1280,46 @@ bool TestIntegerOps()
std::cout << "FAILED:";
std::cout << " Exponentiation operations\n";
// ****************************** 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<COUNTOF(bitCounts); ++i)
{
result = true;
unsigned int maxBits = 0;
const size_t bitCount = bitCounts[i];
Integer n;
for (size_t j=0; j<128; ++j)
{
n.Randomize(prng, bitCount);
maxBits = (std::max)(maxBits, n.BitCount());
}
result &= (maxBits == bitCount);
if (!result)
std::cout << "FAILED: Randomize " << bitCount << "-bits\n";
pass &= result;
}
}
catch (const Exception&)
{
pass = false;
result = false;
}
if (!pass)
std::cout << "FAILED:";
else
std::cout << "passed:";
std::cout << " Randomize of various bit lengths\n";
return pass;
}
#endif