获取每次运行不同的随机字节。

huangapple go评论71阅读模式
英文:

Get different random bytes each run

问题

我想在C++中生成一堆随机字节。为此,我使用以下代码:

```c++
#include <climits>
#include <functional>
#include <random>
#include <vector>
#include <iostream>

using random_bytes_engine = std::independent_bits_engine<
    std::default_random_engine, CHAR_BIT, unsigned char>;

int main()
{
    random_bytes_engine rbe;
    std::vector<unsigned char> data(10);
    std::generate(begin(data), end(data), std::ref(rbe));

    for(int b: data) {
      std::cout << b << ", ";
    }
    std::cout << std::endl;
}
166, 240, 216, 41, 129, 199, 215, 253, 66, 76,

不错。现在,我想确保每次运行程序时都获得不同的值,也就是说,我想从某个地方对independent_bits_engine进行种子化。

有任何提示吗?解决方案必须跨平台。(除了independent_bits_engine之外的可移植解决方案也可以使用。)


<details>
<summary>英文:</summary>

I&#39;d like to generate a bunch of random bytes in C++. For this, I use

```c++
#include &lt;climits&gt;
#include &lt;functional&gt;
#include &lt;random&gt;
#include &lt;vector&gt;
#include &lt;iostream&gt;

using random_bytes_engine = std::independent_bits_engine&lt;
    std::default_random_engine, CHAR_BIT, unsigned char&gt;;

int main()
{
    random_bytes_engine rbe;
    std::vector&lt;unsigned char&gt; data(10);
    std::generate(begin(data), end(data), std::ref(rbe));

    for(int b: data) {
      std::cout &lt;&lt; b &lt;&lt; &quot;, &quot;;
    }
    std::cout &lt;&lt; std::endl;
}
166, 240, 216, 41, 129, 199, 215, 253, 66, 76,

Nice. Now, I'd like to make sure that I get different values each time I run the program, i.e., I'd like to seed the independent_bits_engine from somewhere.

Any hints? The solution must be cross-platform. (Portable solutions other than independent_bits_engine would also work.)

答案1

得分: 1

文档中有一个示例,但它略微隐藏,因为它是为构造函数而提到的,而不是为主类:

std::random_device rd;
std::independent_bits_engine&lt;std::mt19937, /*bits*/ 3, unsigned long&gt; e3(rd()); // 由rd()种子化

这里的random_device实例代表特定于系统的随机数生成器,如此处所指定。当然,您仍然需要验证是否存在这样的随机数生成器,但我想这是在不使用特定于系统的功能的情况下获得的最随机的情况。有关生成的随机性的安全性的讨论可以在这里找到。

英文:

There is an example in the documentation, but it is slightly hidden as it is mentioned for the constructor, not for the main class:

std::random_device rd;
std::independent_bits_engine&lt;std::mt19937, /*bits*/ 3, unsigned long&gt; e3(rd()); // seeded with rd()

Where the instance of random_device represents the system specific random number generator, as specified here. Of course, you'd still have to verify that there is such a random number generator present, but I guess this is about as random as it gets without using system specific functionality. A discussion on the security of the randomness generated can be found here.

huangapple
  • 本文由 发表于 2023年2月23日 22:31:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546218.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定