关于random设备还有一些可说的,那就是系统安全。有人居然能通过系统启动过程或者系统运行的某段时间产生的熵的内容来破译出某些信息,这听起来相当高深,不过理论上来讲却完全可能。因为random设备虽然是通过系统噪声来得到熵,但是如果两次系统启动完全一致,那么启动过程中生成的熵当然会完全一致。不过这些安全漏洞不用我们担心,因为现在的系统都有相关的补丁。
#include
#include
#include
void init_random ()
...{
unsigned int ticks;
struct timeval tv;
int fd;
gettimeofday (&tv, NULL);
ticks = tv.tv_sec + tv.tv_usec;
fd = open ("/dev/urandom", O_RDONLY);
if (fd > 0)
...{
unsigned int r;
int i;
for (i = 0; i < 512; i++)
...{
read (fd, &r, sizeof (r));
ticks += r;
}
close (fd);
}
srand (ticks);
printf("init finished ");
}
unsigned int new_rand ()
...{
int fd;
unsigned int n = 0;
fd = open ("/dev/urandom", O_RDONLY);
if (fd > 0)
...{
read (fd, &n, sizeof (n));
}
close (fd);
return n;
}
int main ()
...{
int n, i;
init_random ();
n = rand ();
printf ("n=%d ", n);
for(i=0;i<10;i++)
printf ("%u ", new_rand());
}
