简体   繁体   English

如何生成12个字节的随机数?

[英]How to generate Random number of 12 bytes?

I'm working on project on linux in C and in which i need to generate random number of 12 bytes. 我正在C中的Linux上的项目中,我需要生成12个字节的随机数。 I have searched over internet but i couldn't find any other than srand or random function. 我已经在互联网上进行搜索,但是除了求职或随机函数外,我找不到其他任何内容。 But these functions can only generate random number of 32-bit(4 byte). 但是这些函数只能生成随机数的32位(4字节)。

I'm looking for generating random number of 12 byte. 我正在寻找生成12字节的随机数。

Does anybody know anything library on linux which provide this functionality ? 有人知道Linux上提供此功能的任何库吗?

OK so finally a solution: 好的,所以最后一个解决方案:

unsigned char buf[12];
int i;
srand(time(NULL));
for (i = 0; i < sizeof(buf); i++) {
    buf[i] = rand() % 256;
}

(Yes, I'm using modulo - if you care about uniform distribution, don't use it.) (是的,我正在使用模数-如果您关心均匀分布,请不要使用它。)

You did not tell what 12 random bytes mean to you, and why you need them. 您没有说出12个随机字节对您意味着什么,以及为什么需要它们。

You should read random(4) then perhaps code 您应该阅读random(4)然后编写代码

unsigned char myrandbytes[12];
FILE* fr = fopen("/dev/urandom", "r");
if (!fr) perror("urandom"), exit(EXIT_FAILURE);
fread(myrandbytes, sizeof(char), 12, fr);
fclose(fr), fr = NULL;

But very often, using rand(3) as suggested in that answer should be enough. 但是通常,按照该答案的建议使用rand(3)应该足够了。 You could also use random(3) or lrand48(3) . 您也可以使用random(3)lrand48(3) I am usually happy enough with random(3) which I usually seed -eg with srandom or initstate by reading /dev/urandom at start time. 我通常对random(3)感到满意,我通常会在开始时通过读取/dev/urandom进行random(3) srandominitstate ,例如使用srandominitstate状态。

Since you did not tell us why you need random numbers, we cannot help more. 由于您没有告诉我们为什么需要随机数,因此我们无能为力。

If the quality of the random number is very important (eg for strong cryptographic purposes), it might be much more hard than you think, and it is system and hardware dependent (read again the random(4) page). 如果随机数的质量非常重要(例如,出于强大的加密目的),则它可能比您想象的要难得多,并且取决于系统和硬件(请再次阅读random(4)页)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM