Below is the implementation of RandomNumberGenerator::GenerateWord32 from 
cryptlib.h.

I know fair shuffling routines can be tricky. Fisher-Yates has some 
non-obvious logic to avoid it, but I'm not sure about the interaction 
between GenerateBlock and Crop. See, for example, 
https://security.stackexchange.com/questions/68044/secure-shuffles-and-the-rand-function.

QUESTION: Does it have a bias?

I thought the count of elements in the range [a,b] is given by b - a + 1 
(and not just b - a).

QUESTION: does it provide all values in the range, inclusive.

**********

//! generate a random 32 bit word in the range min to max, inclusive
word32 GenerateWord32(word32 a=0, word32 b=0xffffffffL);

word32 RandomNumberGenerator::GenerateWord32(word32 min, word32 max)
{
    word32 range = max-min;
    const unsigned int maxBits = BitPrecision(range);

    word32 value;

    do
    {
        GenerateBlock((byte *)&value, sizeof(value));
        value = Crop(value, maxBits);
    } while (value > range);

    return value+min;
}

**********

Here's a test program that tries to expose it. Unfortunately, I cannot run 
it at the moment due to a GDB crash 
(https://bugs.launchpad.net/ubuntu/+source/gdb/+bug/1472558):

static const word32 MIN_VAL = 0, MAX_VAL = 2;
static const word32 RANGE = MAX_VAL - MIN_VAL + 1;
static const unsigned int ITERATIONS = 100000;

int main(int argc, char* argv[])
{
    try {

        RandomNumberGenerator rng;
        vector<unsigned int>buckets;
        buckets.resize(RANGE);

        for(unsigned int i = 0; i < ITERATIONS; i++)
            buckets[rng.GenerateWord32(MIN_VAL, MAX_VAL)]++;

        for(unsigned int j = 0; j < RANGE; j++)
            cout << j << ": " << buckets[j] << endl;
    }
    catch(CryptoPP::Exception& ex)
    {
        cerr << ex.what() << endl;
    }

    return 0;
}

-- 
-- 
You received this message because you are subscribed to the "Crypto++ Users" 
Google Group.
To unsubscribe, send an email to [email protected].
More information about Crypto++ and this group is available at 
http://www.cryptopp.com.
--- 
You received this message because you are subscribed to the Google Groups 
"Crypto++ Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to