Boost logo

Boost Users :

Subject: Re: [Boost-users] Seeding boost::mt19937 with bytes from CryptoGenRandom
From: e m (e4me4m_at_[hidden])
Date: 2010-02-11 14:12:48


Thank you Steven. While I do not have boost installed on this computer, the
code below compiles and runs as I would expect. Upon each execution, the
value of seed changes. I expect boost::mt19937 rng(seed); will work. And now
I have a very good random seed thanks to your advice.

Your friend,

Ed

#include <iostream>
#include <windows.h>
#include <wincrypt.h>

int main()
{

    HCRYPTPROV hProvider = 0;
    BYTE randomBytes[8];
    CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT);
    CryptGenRandom(hProvider, sizeof(randomBytes), randomBytes);
    CryptReleaseContext(hProvider, 0);

    uint64_t seed;
    memcpy(&seed, &randomBytes[0], sizeof(seed));

    std::cout << seed << std::endl;

    return 0;

}

On Wed, Feb 10, 2010 at 11:58 PM, Steven Watanabe <watanabesj_at_[hidden]>wrote:

> AMDG
>
>
> e m wrote:
>
>> I have a C++ program that uses /dev/urandom on Unix systems to seed
>> boost::mt19937. I'm porting the program to Windows. I can get good, random
>> seed data on Windows similar to random seed data produced from /dev/urandom
>> on Unix systems like so:
>>
>> HCRYPTPROV hProvider = 0;
>> BYTE randomBytes[8];
>> CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
>> CryptGenRandom(hProvider, sizeof(randomBytes), randomBytes);
>> CryptReleaseContext(hProvider, 0);
>>
>> However, I'm running into trouble attempting to pass these randomBytes to
>> boost::mt19937. On Unix I do something similar to this:
>>
>> uint64_t GetSeed()
>> {
>> uint64_t seed;
>> std::ifstream urandom;
>> urandom.open("/dev/urandom");
>> urandom.read(reinterpret_cast<char*> (&seed), sizeof(seed));
>> urandom.close();
>> return seed;
>> }
>>
>> boost::mt19937 rng(GetSeed());
>>
>> That works OK on Unix I think. Could anyone suggest how to get the random
>> data from the Windows CryptoAPI passed to boost::mt19937 as seed data? I
>> don't normally program Windows systems, so this has been a bit of a
>> challenge for me.
>>
>
> Try
>
> uint64_t seed;
> memcpy(&seed, &randomBytes[0], sizeof(seed));
>
> In Christ,
> Steven Watanabe
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net