Same question as Is a rand from /dev/urandom secure for a login key, but with glibc's rand
function instead of /dev/urandom
. And what would be a sufficiently secure seed generator?
2 Answers
No. The PRNG in typical C libraries is designed for speed, not for security. It's usually appropriate for numerical simulations and games (in good-quality implementations — there are implementations out there, mostly old ones, where it's not appropriate for anything), but not for cryptography. A cryptographic PRNG must be unpredictable, i.e. an attacker who generates a series of numbers must not be able to make a good guess at the next number. The typical C library PRNG strives for speed and good statistical properties but not for unpredictability.
As of Glibc 2.7, rand
and friends use a linear congruential PRNG or a linear feedback shift register depending on the available seed length.
To generate key material or any other random number involved in cryptography (including non-secret things like nonces that nonetheless need to be unpredictable), obtain all bits from a crypto-quality RNG. Linux's /dev/urandom
(or any other unix that has /dev/urandom
) is fine for that. You must use it for each byte of each key; using it as a seed of the C library PRNG is not good (there would be a strong correlation between the keys). A library such as OpenSSL is another choice; it'll probably use /dev/urandom
under the hood as a seed but may be a little faster if you're generating large volumes of random data.
-
4Another thing to note (a quite important one, imho) is that the C standard makes no guarantee of the algorithm in question which means that if you switch the libc or compiler or platform you may find yourself in a nasty spot. Just because a particular implementation happens to maybe use something cryptographycally-secure does not mean it is safe to rely on that. When writing something in a language that's implemented in a lot of compilers it makes sense to rely only on what the specification guarantees.– JoeyJul 1, 2011 at 15:44
-
@Joey I thought I'd covered that with “there are implementations out there (…) where it's not appropriate for anything”; do you think my answer needs clarification or reinforcement? Jul 1, 2011 at 21:11
No! rand()
is totally insecure. Using rand()
for this purpose has caused major vulnerabilities in major systems.
Just use /dev/urandom
.