Seeding in mini-gmp
Niels Möller
nisse at lysator.liu.se
Thu Nov 24 16:36:07 UTC 2016
tg at gmplib.org (Torbjörn Granlund) writes:
> Should seeds really be limited to an unsigned long and at the same time
> to 4 bytes? Both limits seem unnecessary.
It's platform dependent. On 64-bit machines, unsigned long is 64 bits
(except windows...), and we read 8 bytes from /dev/random. Which ought
to be enough.
On 32-bit machines, using gmp_randseed_ui limits the seed to 32-bits. If
that's a problem, we need to fix it; I just tried to keep things simple.
> I haven't looked deeper into the code, but if there is a seed function
> which accepts an mpz_t, then please consider using it instead. And then
> follow GMP's example and read 6 bytes of random data from /dev/urandom.
There's gmp_randseed. I guess we could use that. Why 6 bytes (48
bits), and not, e.g., 64 bits?
Hmm, now I realize that it's quite important to be able to feed the same
seed to both 32-bit and 64-bit builds; then it's no good to use
gmp_randseed_ui with a platform-dependent range. I'll have to fix that.
> + /* Unsigned long may be only 32 bits, and then a plain microsecond
> + count would wrap around in only 71 minutes. So instead, xor
> + microseconds with the most significant second bits, which are
> + the least "random". */
> + return tv.tv_sec ^ (tv.tv_usec << 12);
>
> You probably need a cast there, else you'll typically end up with 32-bit
> arithmetic there. (Or even better, use mpz_t here too.)
For this piece of code, I don't think we have much use for more than
32-bits. Iff time_t (type of tv_sec) is 64-bit, we'll use the bits
saying whether or not we're beyond 2038, which isn't particularly
random.
If we switch to using a 48-bit mpz_t instead, we could do this
differently and get a better range. E.g, low 48 bits of 1000000*tv_sec +
tv_usec would wraparound in almost 9 years, and tv_sec + tv_usec << 28
would also fill 48 bits and collide rarely.
Regards,
/Niels
--
Niels Möller. PGP-encrypted email is preferred. Keyid 368C6677.
Internet email is subject to wholesale government surveillance.
More information about the gmp-devel
mailing list