类似于/dev/urandom并带有可配置的种子吗? [英] Something similar to /dev/urandom with configurable seed?
问题描述
我来自/dev/urandom
的 dd
,以便创建具有随机内容的文件.这很好用,但是我希望以后可以通过使用相同的种子再次运行PRNG来重现文件内容.是否有任何可播种的PRNG公开了字符设备?
I'm dd
'ing from /dev/urandom
in order to create files with random contents. This works well, but I would like to be able to reproduce the file contents at some later point by running the PRNG again with the same seed. Is there any seedable PRNG which exposes a character device?
我正在使用最新的Linux 3.X内核.
I'm using recent Linux 3.X kernels.
推荐答案
/dev/urandom
旨在尽可能地不可预测.听起来您想要一个更常规的种子式伪随机数生成器.
/dev/urandom
is designed to be as unpredictable as possible. It sounds like you want a more conventional seeded pseudorandom number generator.
这是我刚用C写的:
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char *endptr;
unsigned long int seed;
if (argc != 2 || *argv[1] == '\0') {
fprintf(stderr, "usage: %s seed\n", argv[0]);
return EXIT_FAILURE;
}
errno = 0;
seed = strtoul(argv[1], &endptr, 0);
if (errno != 0 || *endptr != '\0' || seed > UINT_MAX) {
fprintf(stderr, "%s: invalid seed\n", argv[0]);
return EXIT_FAILURE;
}
srandom((unsigned int) seed);
while (1) {
int i;
long int randomnum = random();
for (i = 0; i < sizeof randomnum; i++) {
if (putchar((randomnum >> (i * CHAR_BIT)) & UCHAR_MAX) == EOF) {
return EXIT_SUCCESS;
}
}
}
}
这是一个程序,而不是设备文件,但其输出格式与您从/dev/urandom
获得的格式相同.您可以将其输出通过管道传递到 dd
,并省略 if
.
This is a program, not a device file, but its output is the same format as you'd get from /dev/urandom
. You can pipe the output from it into dd
and omit if
.
如果您需要提供一个真正随机的种子来提供给程序,您可以像这样从/dev/urandom
中获得bash的一个:
If you need to come up with a truly random seed to supply to the program, you can get one in bash from /dev/urandom
like this:
seed=$(od -vAn -N4 -tu4 </dev/urandom)
用您计算机上的任何 sizeof(unsigned int)
替换4(可能是4).
Replace 4 with whatever sizeof(unsigned int)
is on your machine (it's probably 4).
这篇关于类似于/dev/urandom并带有可配置的种子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!