下面这段代码不断往/dev/random写入数据,观察内核熵池熵值变化。
#include <stdio.h>
#include <stdlib.h>
#include <linux/random.h>
//#include <sys/random.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/time.h>
int main(int argc, char *argv[])
{
int ret;
struct rand_pool_info *pool;
struct timeval tm;
char devName[32] = {"/dev/random"}, buf[1024], rand[1024];
int fd = -1, ent = 0, lastent = 0;
fd = open(devName,O_RDWR);
if(-1 == fd){
printf("open %s failed, errno:%i\n",devName,errno);
return;
}
pool = (struct rand_pool_info *)buf;
pool->buf_size = 16;
pool->entropy_count = 8*pool->buf_size;
memset(pool->buf,0x1e,pool->buf_size);
while(1){
ent = 0;
ret = ioctl(fd,RNDGETENTCNT,&ent);
if(-1 == ret){
break;
}
printf("ent:%i, delta ent:%i\n",ent,ent-lastent);
ret = ioctl(fd,RNDADDENTROPY,pool);
if(-1 == ret){
break;
}
//ret = getrandom(rand,32,GRND_RANDOM);
printf("ret:%i, errno:%i, ent:%i\n",ret,errno,pool->entropy_count);
tm.tv_sec = 0;
tm.tv_usec = 1000;
select(0,NULL,NULL,NULL,&tm);
lastent = ent;
getchar();
}
close(fd);
}
首先 cat /dev/random 消耗完系统熵池中熵。
后执行向熵池写入数据执行效果如下图:
写入同样数据,熵池中熵值增加量并没有采用传入的128币特熵计数,而是由熵池评估数据熵值,增加的熵值随着次数增加递减。
当熵池中熵值小于阈值(cat /proc/sys/kernel/random/write_wakeup_threshold)时,系统会自动收集熵源数据,添加到熵池,增加熵值;
当达到阈值时,系统会停止收集熵源数据,熵池中熵值不会自动继续增加。