简体   繁体   English

如何改善代码以生成安全的随机数?

[英]how can I improve my code to generate secure random numbers?

I am trying to found out what is the best way or library to generate secure random numbers such as secrets in python. 我试图找出什么是生成安全随机数(例如python中的secrets )的最佳方法或库。

I am working on windows 10 using codeblocks. 我正在使用代码块在Windows 10上工作。 I have done this so far: 到目前为止,我已经做到了:

#include <cstdlib> 
#include <ctime> 
#include <iostream>

using namespace std;

int main() 
{ 
    srand((unsigned)time(0)); 
    int i;
    i = (rand()%6)+1; 
    cout << i << "\n"; 
}

I am trying to replicate the same function as secrets from python to generate secure random numbers. 我正在尝试复制与python secrets相同的功能,以生成安全的随机数。

std::rand() does not offer sufficient guarantees for being used in cryptographic applications (aka secure random number): std::rand()没有提供足够的保证可用于加密应用程序(也称为安全随机数):

There are no guarantees as to the quality of the random sequence produced. 不能保证所产生的随机序列的质量。 In the past, some implementations of rand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between 1 and 0 between calls). 过去,rand()的某些实现在产生的序列的随机性,分布和周期方面存在严重缺陷(在一个众所周知的示例中,低阶位在调用之间仅在1和0之间交替)。

You may obtain higher quality random generation using the <random> library. 您可以使用<random>库获得更高质量的随机生成。 But again, the generators used, such as for example the mersene twister is not sufficient for cryptographic use. 但是同样,所使用的发生器,例如, 亚美尼亚捻线器 ,不足以用于加密用途。

So you'd better go for specialized libraries such as OpenSSL . 因此,您最好使用OpenSSL之类的专用库。

Alternatively, given your platform choice, you can use the Windows API, with CryptGenRandom() or, better, the newer BCryptGenRandom() . 或者,根据您的平台选择,您可以将Windows API与CryptGenRandom()一起使用,或者更好的是,将其与更新的BCryptGenRandom()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM