我正在寻找一种在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)
一个
你可以组合两个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以使意图更明确.
屏蔽0x00000000FFFFFFFF和0xFFFFFFFF00000000防止两个数字中的位重叠以防万一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)