C++ Access Linux Random Device to Generate Random Number

 C++ and C provide a rand function to generate random numbers, but we all know that this actually generates a pseudo-random number, so how to generate a true random number?

What is pseudorandom?

 Computers do not generate absolutely random random numbers , computers can only generate "pseudo-random numbers". In fact, an absolutely random random number is just an ideal random number. No matter how the computer develops, it will not generate a series of absolutely random random numbers. Computers can only generate relatively random numbers, known as pseudo-random numbers.
 In short, pseudo-random numbers can be followed regularly in some cases, and in a strict program, such an implementation is not feasible.

How to generate true random numbers?

 True random numbers require us that the generated sequence is unpredictable, so how to get an unpredictable sequence? Since human behavior is unpredictable, the Linux kernel measures the user's input time delay as a random number (such as mouse actions and keyboard input).
 Linux provides us with two random number devices:

  • /dev/random : block the random read process when there is no user input
  • /dev/urandom: never block, generate pseudo-random numbers instead when the user has no input operation.

Code

	
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

using namespace std;
 
int main()
{
    
    
    FILE* f = fopen("/dev/urandom", "rb");
    int pwd_int = 0;
    char pwd_char[10];
    cout << endl;
    fread(&pwd_int, sizeof(int), 1, f);
    fread(pwd_char, sizeof(char), 9, f);
    cout << pwd_int << endl;
    cout << pwd_char << endl;
    cout << endl;
     return 0;
}

Guess you like

Origin blog.csdn.net/qq_43550173/article/details/113782066