获取随机数
说明:C标准的随机数产生函数rand()的随机性很不好,rand()产生的随机数序列存在一个较短的循环周期,因此它的随机数是可预测的。
示例:
void Noncompliant ()
{
enum {len = 12};
char id[len]; /* id will hold the ID, starting with
* the characters "ID" followed by a
* random integer */
int r;
int num;
/* ... */
r = rand(); /* generate a random integer */
num = snprintf(id, len, "ID-%d", r); /* generate the ID */
/* ... */
}
以上代码利用rand()产生一个ID的数字部分,因此这些ID是可预测的并且随机性有很大限制。
推荐做法:
Linux下采取建议读取/dev/random文件来获取真随机数。
void Compliant ()
{
enum {len = 12};
char id[len]; /* id will hold the ID, starting with
* the characters "ID" followed by a
* random integer */
int r = 0;
int num;
/* ... */
int fd;
fd = open ("/dev/random", O_RDONLY);
if (fd > 0)
{
read (fd,&r,sizeof (int)); // generate a random integer from /dev/random
}
close (fd);
num = snprintf(id, len, "ID%-d", r); // generate the ID
/* ... */
}
Windows推荐使用随机数生成函数CryptGenRandom():
#include "Wincrypt.h"
void Compliant ()
{
HCRYPTPROV hCryptProv;
union
{
BYTE bs[sizeof(long int)];
long int li;
} rand_buf;
if (!CryptGenRandom(hCryptProv, sizeof(rand_buf), &rand_buf)
{
/* Handle error */
}
else
{
printf("Random number: %ld\n", rand_buf.li);
}
}