【问题标题】:creating random int by rand通过 rand 创建随机 int
【发布时间】:2014-02-21 22:54:25
【问题描述】:

我想编写一个密码学应用程序并且需要一个函数来创建一个 iv。要创建 iv 我想使用 rand() (即使那不安全,我还是想稍后重写大部分代码)。这导致了我的问题:rand() 只返回从 0 到 RAND_MAX 的值(在我的机器上 RAND_MAX 是 32767),我不知道如果 RAND_MAX >= 65535,我是否可以使用这样的代码:

void generate_iv(unsigned char* char_buf, int len){
    union { //treat char_buf like a short_buf
        unsigned char* char_buf;
        unsigned short* short_buf;
    }
    int i;
    for (i = 0; i < len / 2; i++){ //fill short_buf with random values
        short_buf[i] = (unsigned short) rand();
    }
    if (len & 0x01){ //could not fill char_buf with 2-byte short values completely
        char_buf[len - 1] = (unsigned char) rand();
    }
}

当然,这将在每台机器上轻松编译,但它不会在 RAND_MAX

始终有效的代码是:

void generate_iv(unsigned char* char_buf, int len){
    int i;
    for (i = 0; i < len; i++){
        char_buf = (unsigned char) rand();
    }
}

这段代码应该可以正常工作,但它不像上面的代码那样有效。 我的问题是:在这种情况下,是否有最佳的效率和可移植性?是否有更安全的方式(可能很容易实现)来产生随机数或获得具有恒定大小的随机数?

【问题讨论】:

  • 如果您正在编写加密应用程序,我当然不会推荐rand。有一个漂亮闪亮的 &lt;random&gt; 标头,它的性能要好得多,并且没有可能非常低的最大值(即使 INT_MAX 和 32 位 int 在支持 64 位时也很低)。
  • 您不应该使用rand 进行加密。看看 C++11 random number generation 库。
  • 就像我说的,我只是想使用任何随机函数来测试程序,rand() 只是我想到的第一个。我知道使用 rand 会导致安全性不足。所以我更高兴你向我展示了我的问题的解决方案和一个全新的库来“探索”。
  • 我刚刚编译了一个包含 的程序,我的编译器 (Mingw, g++) 退出并说此功能仍处于试验阶段。我真的可以依靠这个吗?

标签: c++ random


【解决方案1】:

正如您所提到的,rand() 不安全,因此无论该问题如何,我都会提及手头的问题。

鉴于rand() 生成一个 15 位数字,而您想要一个 16 位数字,您可以这样做:

int a = rand();
int b = rand()&1;
return a | (b<<15);

或者一般来说,假设 RAND_MAX &lt; 0xFFFFRAND_MAX+1 是 2 的幂:

int len = BIT_LEN(RAND_MAX);
int mask = (1<<(16-len))-1;
int a = rand();
int b = rand()&mask;
return a | (b<<len);

顺便说一句,不要忘记在程序开始时用一些随机输入为 RNG 播种,例如:

srand((unsigned int)time(NULL));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多