1

I tested the following mini example with MSVC 2017 on Win7:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::cout << "entropy: " << rd.entropy() << std::endl;
    return 0;
}

To my surprise, it outputs "entropy: 32". This means that rd produces real-random numbers instead of pseudo-random numbers. I was expecting "entropy: 0". As far as I understand it, no finite-length code is capable of producing real-random numbers, it takes a real specially-designed physical device to do so. No such device is attached to my testing PC.

My question is: how std::random_device is implemented that it produces real-random number without special hardware support?

John Z. Li
  • 1,893
  • 2
  • 12
  • 19
  • 1
    [here's one impl](https://code.woboq.org/gcc/libstdc++-v3/src/c++11/random.cc.html), and some [more random info](http://www.pcg-random.org/posts/cpps-random_device.html) – gman Oct 29 '18 at 02:47
  • @gman it seems that magic is done by "__x86_rdrand(void)", – John Z. Li Oct 29 '18 at 02:54
  • 2
    The question seems to already have an answer for a previous VC++ version: https://stackoverflow.com/questions/9549357/the-implementation-of-random-device-in-vs2010 – IMil Oct 29 '18 at 02:59
  • 2
    The standard says if the system has a nondeterministic random number source then the implementation of `std::random_device` should use it. Many `OS`s have access to physical random sources through the physical device interfaces. – Galik Oct 29 '18 at 02:59
  • 2
    At least one major implementation swiped [an XKCD comic](https://xkcd.com/221/). – user4581301 Oct 29 '18 at 02:59

1 Answers1

3

Firstly, are you sure there is no specially-designed physical device in your PC? Intel added such hardware to the CPU in 2013, and AMD followed suit in 2015.


Secondly, it is possible to acquire reasonably good entropyby measuring the jitter in timings from physical processes like

  • network packets
  • hard disk (less useful if the hard disk is an SSD)
  • mouse movements
  • keyboard clicks

For a desktop or laptop, acquiring good entropy is really not that hard. Where it becomes more challenging is in constrained environments like a smartcard or an IoT device at first boot (where there have not been many network packets - but you want to generate a good public/private key pair).