random number

Pedro Gimeno gmpdiscuss at personal.formauri.es
Thu Mar 19 00:01:42 CET 2009

José de Jesús Angel Angel wrote:
> Hello
> I would like know if this is the best way for generating a randon number 
> of  160 bits.
> What I have to do for improve this.
> unsigned long int  seed;
> mpz_t  temp;
> gmp_randstate_t state;
> mpz_init(temp);
> gmp_randinit_default(state);
> seed= rand();
> gmp_randseed_ui (state,seed);
> mpz_urandomb(temp, state, 160);
> mpz_out_str (NULL, 10, temp);
> cout << endl;
> mpz_clear(temp);

Ultimately, that code depends on your C library's rand() function, 
meaning that the seeding process depends on how well it's initialized 
and how many random numbers it produces (e.g. if RAND_MAX equals 32767, 
you can't get more than 32768 different random numbers in total and it's 
likely that one of them will be repeated in about 180 steps or so).

Other than that, the code looks fine. Just don't use it for 
cryptographic purposes. If your intention is cryptographic, I suggest 
you use OpenSSL instead to generate random numbers. Use this command to 
obtain a base64-encoded 160-bit string:

  openssl rand -base64 20

Or just omit the -base64 switch to obtain a binary dump of 20 bytes (160 
bits) which you can write to file with the -out switch.

-- Pedro Gimeno

More information about the gmp-discuss mailing list