如何生成大的随机数C.

gfp*_*ste 9 c random rsa

我正在寻找一种在C ...(100000000 - 999999999)中生成大约2 ^ 64的大随机数的方法,用于公钥加密算法(如p和q).

我不想生成小于2 ^ 64的数字(即小于100000000).

有什么能帮我做到这一点吗?

Dav*_*dek 13

random()返回一个长度,在64位系统上应该是64位.如果您使用的是32位系统,则可以执行以下操作:

#include <inttypes.h>

uint64_t num;

/* add code to seed random number generator */

num = rand();
num = (num << 32) | rand();

// enforce limits of value between 100000000 and 999999999
num = (num % (999999999 - 100000000)) + 100000000;
Run Code Online (Sandbox Code Playgroud)

或者在NIX系统上,您可以将/ dev/random读入缓冲区:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <inttypes.h>   

int fd;
uint64_t num; 
if ((fd = open("/dev/random", O_RDONLY) == -1)
{
    /* handle error */
};
read(fd, &num, 8);
close(fd);

// enforce limits of value between 100000000 and 999999999
num = (num % (999999999 - 100000000)) + 100000000;
Run Code Online (Sandbox Code Playgroud)

一个

  • `rand()`受`RAND_MAX`限制,不需要`2 ^ 32`.并且,你仍然需要传递给`srand()`.`/ dev/random`功能也可以在[其他平台](http://en.wikipedia.org/wiki//dev/random)上找到. (5认同)
  • 在我的电脑上``RAND_MAX`是'2 ^ 31`,而不是'2 ^ 32`. (3认同)
  • 更好,但现在805933941(2 ^ 64 -1 mod 899999999)以上的数字比下面的数字略差;-) (2认同)

Bla*_*iev 9

你可以组合两个4字节的随机整数来产生一个8字节的整数:

#include <stdint.h>
...
uint64_t random = 
  (((uint64_t) rand() <<  0) & 0x00000000FFFFFFFFull) | 
  (((uint64_t) rand() << 32) & 0xFFFFFFFF00000000ull);
Run Code Online (Sandbox Code Playgroud)

rand返回以来int,sizeof(int) >= 4几乎在任何现代平台上,此代码都应该有效.我添加了<< 0以使意图更明确.

屏蔽0x00000000FFFFFFFF0xFFFFFFFF00000000防止两个数字中的位重叠以防万一sizeof(int) > 4.

编辑

既然@Banthar评论说RAND_MAX不一定2 ^ 32,并且我认为至少2 ^ 16可以保证,你可以将四个2字节数组合起来以确保:

uint64_t random = 
  (((uint64_t) rand() <<  0) & 0x000000000000FFFFull) | 
  (((uint64_t) rand() << 16) & 0x00000000FFFF0000ull) | 
  (((uint64_t) rand() << 32) & 0x0000FFFF00000000ull) |
  (((uint64_t) rand() << 48) & 0xFFFF000000000000ull);
Run Code Online (Sandbox Code Playgroud)

  • 如果使用`^`来组合数字而不是`|`,则无需担心屏蔽. (4认同)

wkl*_*wkl 7

您正在寻找加密强度的PRNG,例如openssl/rand:http://www.openssl.org/docs/crypto/rand.html