There is no cross-platform solution. On Linux, read from /dev/urandom
(with fread
, or with read
if you have a taste for complexity). The bytes read from /dev/urandom
are suitable for cryptographic use except from a freshly-started embedded system or server lacking entropy.
The documentation is overly conservative (stemming from a theoretical notion of security where the attacker has infinite computation power rather than merely the use of all the computers int he world); in most situations, it is perfectly fine to use /dev/urandom
to generate cryptographic keys.
If you need to generate a lot of random bytes, you may want to implement a pseudo-random number generator inside your code, and use /dev/urandom
only to seed it with entropy. If you're just generating a few keys and similar small amounts of material, or if you need to generate a lot of random numbers but the speed of /dev/urandom
isn't a bottleneck, or if this is a school exercise and implementing a PRNG is not the point of the exercise, then just reading from /dev/urandom
is fine.