2

In C++, how can we make std::uniform_int_distribution cryptographically secure? For example is the following code generate cryptographically secure uniformly random numbers? If not, how can we correct it?

#include <iostream>
#include <random>

int main(void){
  std::default_random_engine generator;
  std::uniform_int_distribution<int> distribution(0,9);
  int p[10]={};

  for (int i=0; i<10; ++i) {
    int number = distribution(generator);
    ++p[number];
  }
}
user9414424
  • 498
  • 3
  • 15
  • This might be a better question for [InformationSecurity.SE](https://security.stackexchange.com/help/on-topic) If you do decide to post there, please delete the question here. – NathanOliver Nov 01 '19 at 14:47
  • google NIST SP 800-22 – Andrew Kashpur Nov 01 '19 at 14:48
  • why do you want a uniform int from a CSPRNG? especially in that range! CSPRNGs aren't designed to produce uniformly distributed output, they aim for output that is difficult to predict. if you care about statistical properties then use an RNG designed for it – Sam Mason Nov 01 '19 at 16:39

1 Answers1

2

None of the random engines provided in the C++ standard are "cryptographically secure", and even std::random_device is specified only to generate "nondeterministic" random numbers (at best), without necessarily imposing any particular security requirements.

In particular, uniform_int_distribution (as with all other C++ distribution classes) has implementation-defined behavior. For example, an implementation of the C++ standard library may implement uniform_int_distribution using rejection sampling or another strategy. This means that uniform_int_distribution is not guaranteed to be "constant-time" from a security point of view (in the sense that differences in running time cannot be exploited in a security attack; for example, in a way that could recover the random seed).

Peter O.
  • 32,158
  • 14
  • 82
  • 96
  • Thanks for your kind answer! What determines the implementation? Compiler? – user9414424 Nov 01 '19 at 15:38
  • 1
    The C++ standard library implementation decides how `std::uniform_int_distribution` (as with other C++ distribution classes) is implemented. – Peter O. Nov 01 '19 at 15:43