有没有一个函数生成一个随机int数在C?或者我必须使用第三方库?
当前回答
如果您需要128个安全随机位,符合RFC 1750的解决方案是读取已知可以生成可用熵位的硬件源(例如旋转磁盘)。更好的是,好的实现应该使用混合函数组合多个源,并最终通过重新映射或删除输出来消除输出分布的倾斜。
如果你需要更多的比特,你需要做的就是从128个安全随机比特的序列开始,并将其拉伸到所需的长度,将其映射到人类可读的文本等等。
如果你想在C中生成一个安全的随机数,我将遵循这里的源代码:
https://wiki.sei.cmu.edu/confluence/display/c/MSC30-C.+Do+not+use+the+rand%28%29+function+for+generating+pseudorandom+numbers
注意,对于Windows bbcryptgenrandom是使用的,而不是CryptGenRandom,在过去的20年里已经变得不安全。您可以亲自确认BCryptGenRandom符合RFC 1750。
For POSIX-compliant operating systems, e.g. Ubuntu (a flavor of Linux), you can simply read from /dev/urandom or /dev/random, which is a file-like interface to a device that generates bits of entropy by combining multiple sources in an RFC 1750 compliant fashion. You can read a desired number of bytes from these "files" with read or fread just like you would any other file, but note that reads from /dev/random will block until a enough new bits of entropy are available, whereas /dev/urandom will not, which can be a security issue. You can get around that by checking the size of the available entropy pool, either my reading from entropy_avail, or by using ioctl.
其他回答
下面是我的方法(围绕rand()的包装器):
我还扩展到允许min为INT_MIN而max为INT_MAX的情况,这通常不可能单独使用rand(),因为它返回从0到RAND_MAX的值,包括(1/2范围)。
像这样使用它:
const int MIN = 1;
const int MAX = 1024;
// Get a pseudo-random number between MIN and MAX, **inclusive**.
// Seeding of the pseudo-random number generator automatically occurs
// the very first time you call it.
int random_num = utils_rand(MIN, MAX);
定义和氧描述:
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
/// \brief Use linear interpolation to rescale, or "map" value `val` from range
/// `in_min` to `in_max`, inclusive, to range `out_min` to `out_max`, inclusive.
/// \details Similar to Arduino's ingenious `map()` function:
/// https://www.arduino.cc/reference/en/language/functions/math/map/
///
/// TODO(gabriel): turn this into a gcc statement expression instead to prevent the potential for
/// the "double evaluation" bug. See `MIN()` and `MAX()` above.
#define UTILS_MAP(val, in_min, in_max, out_min, out_max) \
(((val) - (in_min)) * ((out_max) - (out_min)) / ((in_max) - (in_min)) + (out_min))
/// \brief Obtain a pseudo-random integer value between `min` and `max`, **inclusive**.
/// \details 1. If `(max - min + 1) > RAND_MAX`, then the range of values returned will be
/// **scaled** to the range `max - min + 1`, and centered over the center of the
/// range at `(min + max)/2`. Scaling the numbers means that in the case of scaling,
/// not all numbers can even be reached. However, you will still be assured to have
/// a random distribution of numbers across the full range.
/// 2. Also, the first time per program run that you call this function, it will
/// automatically seed the pseudo-random number generator with your system's
/// current time in seconds.
/// \param[in] min The minimum pseudo-random number you'd like, inclusive. Can be positive
/// OR negative.
/// \param[in] max The maximum pseudo-random number you'd like, inclusive. Can be positive
/// OR negative.
/// \return A pseudo-random integer value between `min` and `max`, **inclusive**.
int utils_rand(int min, int max)
{
static bool first_run = true;
if (first_run)
{
// seed the pseudo-random number generator with the seconds time the very first run
time_t time_now_sec = time(NULL);
srand(time_now_sec);
first_run = false;
}
int range = max - min + 1;
int random_num = rand(); // random num from 0 to RAND_MAX, inclusive
if (range > RAND_MAX)
{
static_assert(
sizeof(long int) > sizeof(int),
"This must be true or else the below mapping/scaling may have undefined overflow "
"and not work properly. In such a case, try casting to `long long int` instead of "
"just `long int`, and update this static_assert accordingly.");
random_num = UTILS_MAP((long int)random_num, (long int)0, (long int)RAND_MAX, (long int)min,
(long int)max);
return random_num;
}
// This is presumably a faster approach than the map/scaling function above, so do this faster
// approach below whenever you don't **have** to do the more-complicated approach above.
random_num %= range;
random_num += min;
return random_num;
}
参见:
[我在写下上面的答案后发现了这个问答,但它显然非常相关,他们对非缩放范围的情况做了同样的事情]我如何从rand()中获得特定的数字范围? [我需要进一步研究和阅读这个答案-似乎有一些好的观点,保持良好的随机性不使用模量]我如何从rand()得到一个特定的数字范围? http://c-faq.com/lib/randrange.html
如果你的系统支持arc4random函数族,我建议使用它们来代替标准的rand函数。
arc4random家族包括:
uint32_t arc4random(void)
void arc4random_buf(void *buf, size_t bytes)
uint32_t arc4random_uniform(uint32_t limit)
void arc4random_stir(void)
void arc4random_addrandom(unsigned char *dat, int datlen)
Arc4random返回一个随机的32位无符号整数。
Arc4random_buf将随机内容放在参数buf: void *中。内容的数量由bytes: size_t参数决定。
Arc4random_uniform返回一个随机的32位无符号整数,它遵循规则:0 <= Arc4random_uniform (limit) < limit,其中limit也是一个32位无符号整数。
Arc4random_stir从/dev/urandom读取数据,并将数据传递给arc4random_adrandom以额外随机化它的内部随机数池。
arc4random_adrandom由arc4random_stir使用,根据传递给它的数据填充它的内部随机数池。
如果你没有这些函数,但你在Unix上,那么你可以使用下面的代码:
/* This is C, not C++ */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h> /* exit */
#include <stdio.h> /* printf */
int urandom_fd = -2;
void urandom_init() {
urandom_fd = open("/dev/urandom", O_RDONLY);
if (urandom_fd == -1) {
int errsv = urandom_fd;
printf("Error opening [/dev/urandom]: %i\n", errsv);
exit(1);
}
}
unsigned long urandom() {
unsigned long buf_impl;
unsigned long *buf = &buf_impl;
if (urandom_fd == -2) {
urandom_init();
}
/* Read sizeof(long) bytes (usually 8) into *buf, which points to buf_impl */
read(urandom_fd, buf, sizeof(long));
return buf_impl;
}
urandom_init函数打开/dev/urandom设备,并将文件描述符放在urandom_fd中。
urandom函数基本上与rand调用相同,只是更安全,并且它返回一个长(容易更改)。
但是,/dev/urandom可能会有点慢,所以建议您使用它作为不同随机数生成器的种子。
如果您的系统没有/dev/urandom,但是有一个/dev/random或类似的文件,那么您可以简单地将传递的路径更改为在urandom_init中打开。urandom_init和urandom中使用的调用和api(我相信)是POSIX兼容的,因此,即使不是所有POSIX兼容的系统,也应该在大多数系统上工作。
注意:如果可用熵不足,从/dev/urandom读取将不会阻塞,因此在这种情况下生成的值可能是密码不安全的。如果您担心这一点,那么使用/dev/random,如果熵不足,它总是会阻塞。
如果您在另一个系统(即。Windows),然后使用rand或一些内部Windows特定平台依赖的不可移植API。
urandom, rand或arc4random调用的包装器函数:
#define RAND_IMPL /* urandom(see large code block) | rand | arc4random */
int myRandom(int bottom, int top){
return (RAND_IMPL() % (top - bottom)) + bottom;
}
我们来看看这个。首先,我们使用srand()函数来为随机化器播种。基本上,计算机可以根据输入给srand()的数字生成随机数。如果你给出相同的种子值,那么每次都会生成相同的随机数。
因此,我们必须用一个总是在变化的值来给随机化器播种。我们通过time()函数将当前时间的值提供给它来实现这一点。
现在,当我们调用rand()时,每次都会产生一个新的随机数。
#include <stdio.h>
int random_number(int min_num, int max_num);
int main(void)
{
printf("Min : 1 Max : 40 %d\n", random_number(1,40));
printf("Min : 100 Max : 1000 %d\n",random_number(100,1000));
return 0;
}
int random_number(int min_num, int max_num)
{
int result = 0, low_num = 0, hi_num = 0;
if (min_num < max_num)
{
low_num = min_num;
hi_num = max_num + 1; // include max_num in output
} else {
low_num = max_num + 1; // include max_num in output
hi_num = min_num;
}
srand(time(NULL));
result = (rand() % (hi_num - low_num)) + low_num;
return result;
}
如果您需要128个安全随机位,符合RFC 1750的解决方案是读取已知可以生成可用熵位的硬件源(例如旋转磁盘)。更好的是,好的实现应该使用混合函数组合多个源,并最终通过重新映射或删除输出来消除输出分布的倾斜。
如果你需要更多的比特,你需要做的就是从128个安全随机比特的序列开始,并将其拉伸到所需的长度,将其映射到人类可读的文本等等。
如果你想在C中生成一个安全的随机数,我将遵循这里的源代码:
https://wiki.sei.cmu.edu/confluence/display/c/MSC30-C.+Do+not+use+the+rand%28%29+function+for+generating+pseudorandom+numbers
注意,对于Windows bbcryptgenrandom是使用的,而不是CryptGenRandom,在过去的20年里已经变得不安全。您可以亲自确认BCryptGenRandom符合RFC 1750。
For POSIX-compliant operating systems, e.g. Ubuntu (a flavor of Linux), you can simply read from /dev/urandom or /dev/random, which is a file-like interface to a device that generates bits of entropy by combining multiple sources in an RFC 1750 compliant fashion. You can read a desired number of bytes from these "files" with read or fread just like you would any other file, but note that reads from /dev/random will block until a enough new bits of entropy are available, whereas /dev/urandom will not, which can be a security issue. You can get around that by checking the size of the available entropy pool, either my reading from entropy_avail, or by using ioctl.
你也可以使用mathgl库#include <mgl2/mgl_cf.h>(虽然首先你需要安装它,我自己通过MSYS2安装)函数mgl_rnd()。它也有均匀分布,高斯分布等等。这是ez的用法。但我不知道它的特点。
推荐文章
- C多行宏:do/while(0) vs作用域块
- 生成具有给定(数值)分布的随机数
- time_t最终的类型定义是什么?
- 我需要显式处理负数或零时,总和平方数字?
- 函数名周围的括号是什么意思?
- 用C语言创建自己的头文件
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- main()中的Return语句vs exit()
- 如果不是内存地址,C指针到底是什么?
- 在php中生成一个随机密码
- GLSL的随机/噪声函数
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- java.util.Random和java.security. securerrandom的区别
- 保护可执行文件不受逆向工程的影响?
- 0到1之间的随机数?