Random long long generator C++ [closed]

2019-02-21 06:03发布

What is a solution to generate random long long with cryptographic strength С++? (boost is allowed)

标签: c++ random int64
2条回答
Emotional °昔
2楼-- · 2019-02-21 06:39

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;
查看更多
smile是对你的礼貌
3楼-- · 2019-02-21 06:51

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.

查看更多
登录 后发表回答