What is a solution to generate random long long
with cryptographic strength С++? (boost is allowed)
问题:
回答1:
The <random>
header provides portable access to random number facilities including, potentially, a cryptographic pRNG.
#include <random> // random_device, uniform_int_distribution
#include <algorithm> // generate_n
#include <iterator> // ostream_iterator
#include <iostream> // cout
#include <functional> // bind, ref
int main() {
std::random_device r;
std::uniform_int_distribution<long long> dist;
std::generate_n(std::ostream_iterator<long long>(std::cout, "\n"), 10,
std::bind(dist,std::ref(r)));
}
std::random_device
may not be a cryptographic pRNG on all implementations, so you'll have to check your implementation documentation. In particular VC++ before 2012 does not provide a non-deterministic implementation. VC++ 2012 and later implements this using Windows cryptography services.
Implementations on other operating systems such as Linux or Mac OS X can commonly use "/dev/urandom" or "/dev/random" or any other random device exposed via the filesystem. E.g. libc++ uses "/dev/urandom" by default, which on OS X uses the Yarrow algorithm.
I know you ruled out boost, but boost::random_device
has an implementation for Windows that uses that platform's cryptography services.
回答2:
Under linux you can read from /dev/random
or /dev/urandom
They both provide cryptographic entropy.
Difference between them being: /dev/random
blocks if entropy is exhausted, therefore it could be slower than /dev/urandom
but is "stronger"
So, using streams it will look like this
long long n;
std::ifstream rstream ("/dev/random");
rstream >> n;