问题描述
我正在尝试为公钥和私钥生成大的随机数。我对在客户端生成随机 256 位私钥的初始种子有问题。
您可能知道,我们不应该在 C 中使用 rand
或 srand
函数,因为它们很容易被破坏。
如何生成随机种子以生成随机的 256 位私钥?
我在 C 中使用 GMP 的线性同余算法生成随机数。
解决方法
在 unix 系统上,您可以从 /dev/random
和 /dev/urandom
文件中读取以获取一些“随机性”字节序列。这些序列基于您的系统熵。
请参阅 this 帖子了解有关它们之间差异的更多详细信息。
#include <unistd.h> // read
#include <fcntl.h> // open
#include <stdio.h> // printf
int main(void)
{
int fd;
unsigned int seed;
fd = open("/dev/urandom",O_RDONLY);
read(fd,&seed,sizeof seed);
printf("%u\n",seed);
// Then you can use srand with your new random seed
return (0);
}
注意:打开阅读后不要忘记检查错误,使用后不要忘记关闭fd
。