Skip to content

Commit

Permalink
Remove unneeded check in Integer::Randomize(bitCount) (GH #1206)
Browse files Browse the repository at this point in the history
Update docs to specify case when bitCount==0
Add tests for Randomize function in debug builds
  • Loading branch information
noloader committed Jun 25, 2023
1 parent 3f36b1d commit 6ac6668
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 3 deletions.
8 changes: 6 additions & 2 deletions integer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
1 change: 1 addition & 0 deletions integer.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 <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
Expand Down
42 changes: 41 additions & 1 deletion validat2.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<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

Expand Down

0 comments on commit 6ac6668

Please sign in to comment.