-2

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

Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
Roman
  • 69
  • 4
  • 10

2 Answers2

6

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.

bames53
  • 86,085
  • 15
  • 179
  • 244
  • 1
    +1 for using std but also pointing to boost again (I don't understand why people don't have boost setup by default) – gvd Dec 04 '12 at 18:11
  • @gvd: Many companies do not like putting open source code onto the build machine. – Mooing Duck Dec 04 '12 at 19:16
3

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;
Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281