What is the easiest way to generate a pseudo-rando

2019-08-06 14:30发布

I need to generate random numbers for a student homework in cryptography.

At first I wanted to use

srand(time(NULL));
int r = rand();

But I read that shouldn't use it for cryptography. I'd like if possible to not write my own pseudo-random number generator.

What is the fastest/easiest way to generate pseudo-random numbers in C for cryptographic purposes?

I'm on Linux and I don't mind if the answer isn't cross-platform.

2条回答
贼婆χ
2楼-- · 2019-08-06 14:47

Only having a Pseudo Random Number Generator is not enough. You need to seed it with enough entropy to start it up. You do this by setting a seed generally retrieved from one of the operating system calls. Which one you should use depends on the method that you use it. You can mix in seed later if you want even higher quality random numbers.

For Linux systems: /dev/random returns the most entropy, /dev/urandom is itself a seeded PRNG and may be used directly by applications. /dev/random however blocks if not enough entropy is available, I would advice /dev/urandom for most purposes. Reading too much from /dev/random/ can bring down an entire machine as anything that requests entropy from it may stall. On other operating systems both /dev/random /dev/urandom simply link to a seeded PRNG.

For Windows take a look at this article on MSDN.

查看更多
来,给爷笑一个
3楼-- · 2019-08-06 15:02

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.

查看更多
登录 后发表回答