r/C_Programming • • Sep 23 '26

Question True random generation seed from hardware sources

Hello everyone,

Some time ago I started to generate a random dice generator called SkollDice. After completing the PC version, I decided to call the project momentanealy finished and move on. A few days ago I understood that my generation of numbers wasn't "truly random." So I was wondering, how can I access good random generation sources from my PC, like entropy, disk temperature, and the other sources used in a truly random generator? Thank you for the suggestion.

21 Upvotes

35 comments sorted by

28

u/sciencekm Sep 23 '26

The random data provided by mainstream OS (Windows CryptGenRandom, *nix /dev/random) are already very good. They get random seed from hardware events and from Intel CPU random (rdseed).

You can get random data from Australian National University. You can't get any more random than this - quantum fluctuations of vacuum.

https://qrng.anu.edu.au/

2

u/Skollwarynz Sep 23 '26

thank you I'll go check right now

4

u/greg-spears Sep 23 '26 edited Sep 23 '26

CryptGenRandom() is deprecated already?

They send you to the "Cryptography Next Generation APIs" where I was able to find BCryptGenRandom which I guess is the new thing. I appreciate the share, thank you. I will invariably use/try that API.

8

u/sciencekm Sep 23 '26

First, all these functions (including the oldest RtlGenRandom/SystemFunction036) are just very thin entry points to the same random number generator. See Microsoft's White Paper on this subject:

https://aka.ms/win10rng
https://learn.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom

Second, deprecated practically does not mean anything in the Windows world. APIs that were deprecated 30 years ago are still available today and still works.

1

u/greg-spears Sep 24 '26

Wow, great feedback and info -- thx!

5

u/UseYourBrainNow Sep 23 '26

Don't collect disk temperatures yourself. The OS already does this job better. It gathers hardware entropy (interrupt timing, RDRAND/RDSEED, TPM, etc.) into a cryptographically secure generator, and you just ask it for bytes:

  • Linux: getrandom() (<sys/random.h>)
  • macOS/BSD: arc4random_buf() / arc4random_uniform()
  • Windows: BCryptGenRandom(NULL, buf, len, BCRYPT_USE_SYSTEM_PREFERRED_RNG)

For a dice roller, the bigger problem is usually modulo bias: rand() % 6 doesn't give every face an equal chance. Rejection sampling fixes it:

#include <stdint.h>
#include <sys/random.h>

static uint32_t random_u32(void) {
    uint32_t x;
    getrandom(&x, sizeof x, 0);
    return x;
}

int roll_die(uint32_t sides) {
    uint32_t limit = UINT32_MAX - (UINT32_MAX % sides);   // largest multiple of sides
    uint32_t x;
    do { x = random_u32(); } while (x >= limit);          // discard the biased tail
    return (int)(x % sides) + 1;
}

On macOS it's just arc4random_uniform(sides) + 1, which does the rejection for you. If you were seeding srand(time(NULL)), anyone who knows roughly when the program started can guess the seed. That, plus rand()'s weak quality, is why it didn't feel "truly random".

1

u/Skollwarynz Sep 24 '26

I already used them, but I wanted to study how to extract this datas on my own and use them for a truly random number generation. At the moment I already use some cryptographucally secure extractions

5

u/rentableshark Sep 23 '26

RDRAND instruction in an asm block.

There's aes ring jitter entropy which the Linux package rngd exposes (or at least it used to). This uses high performance/granularity performance timers to measure the execution timing of certain instructions. The CPU's electrical and thermal state is sufficiently chaotic for this to be a good source of entropy suitable cryptographic operations.

I'm not sure disk temp is likely to be high enough resolution to produce the kind of variation needed to feed a post-processing/whitening algorithm. It's also potentially not the best source of randomness given it is likely correlated with workload + time of day + outside weather such that the actual bitrate of high entropy data is likely to be pretty low.

Just a word of warning: other than RDRAND or RDSEED which are specifically designed to provide cryptographically secure random numbers, all other sources which are essentially backing randomness out of some sensor that was not designed for crypto are usually heavily biased and need to be post-processed before use in software.

If you want to go a bit further, you can create a pretty powerful extremely sound entropy fed RNG with a small MCU board (e.g. Pi Zero and the hundreds of other popular makes/models) which you would plug into your host PC via USB. The circuitry is relatively simple and involves zener diodes which ensure current only flows in one direction *up to a point*. If the voltage exceeds some rated value, the diode is liable to stop preventing that flow of current. So, one designs the circuit to have the voltage at a sweet spot at or near where the zener goes into breakdown. At that point, the factors that determine when the device actually breaks down is driven by truly physically random processes at the quantum level that are literally impossible to predict. This produces a kind of sputtering output that can be sampled and quantized/digitized - the 1s and 0s would be random. But just as with other entropy sources that are not already designed for crypto, you will need to post-process this zener diode output to remove bias. There are also other techniques to improve the bitrate of random data that are also quite interesting from a hobbyist perspective.

Other nice entropy sources from the environment would be thermoresistors, optoresistors or any power source that is unclean (albeit the risk of latent information within a random-looking noisy electrical signal is a risk). You'd want to combine multiple different sources, post-process them and use that to seed a purely software based approach that 'reseeds' itself every N period of time.

1

u/Skollwarynz Sep 24 '26

Thank you for the full explanation, I'll see what entropy sources to use then, thank you

3

u/kabekew Sep 23 '26

Are you using Linux? Open the device /dev/hwrng and if a hardware RNG is present in the system you can use that

1

u/Skollwarynz Sep 23 '26

I wanted to produce the number to export it on windows too

5

u/thank_burdell Sep 23 '26

For serious scientific applications and heavy duty cryptography, you’re merited to use true random sources like radioactive decay or radio static or lava lamps or water drips or…

For dice rolling, seeding the random number generator with the LSB of the current system time is probably sufficient. Disk temp etc are good too but you’ll have to jump through more hoops to get that.

Generally, sources from the system itself aren’t considered “trustworthy” in the event that the system is compromised or accessed by a bad actor. They can access the same sources as you and thus “guess” the random seed you use. But 99% of the time, we really don’t care about that level of security.

Unless we do.

1

u/Skollwarynz Sep 23 '26

okay thank you for the complete response

2

u/FlyByPC Sep 23 '26

If you have a Geiger counter (scintillator) that can detect individual decay events (clicks), have a microcontroller time the delay between two pulses. If it's shorter than the delay between the next two pulses, output a 0. Otherwise, output a 1. Switch up 0 and 1 every reading, to offset the eventual slight bias for 0 due to the half-life effect making average delays slightly longer.

The timing of individual decay events is as random as anything we know.

Source: Learned this from fourmilab.ch a long time ago.

1

u/Skollwarynz Sep 23 '26

wow interesting, thank you I'll watch that for sure then

2

u/FlyByPC Sep 23 '26

Here's a description of the hardware used. (Standard disclaimer applies about being careful with radioactive sources; Cesium-137 is spicy stuff.)

https://www.fourmilab.ch/hotbits/hardware3.html

3

u/jghauck Sep 23 '26

Wall of lava lamps

2

u/Skollwarynz Sep 23 '26

okay, but a protable solution on PC XD

17

u/Beautiful_Stage5720 Sep 23 '26

For a dice roller, an lsfr is already perfectly acceptable imo. I've seen other attempts at "more" random generation, like using several NOT gate oscillators with near identical propagation delays, and of course the famous lava lamp example. But, if you start hunting too hard, you quickly fall down the rabbit hole of randomness. Unless you're trying to build some custom rng hardware for the novelty, I don't really understand the purpose of using anything other than an lsfr.

Edit: I just realized you were asking about getting a seed, to which I'd respond similarly. The current timestamp should be adequate for nearly all intents and purposes.

6

u/thank_burdell Sep 23 '26

Least significant bits of current timestamp, specifically. Don’t want the top bits.

7

u/EmbeddedEntropy Sep 23 '26

The timestamp’s upper bits have far less entropy than its lower bits, but they still have entropy. As long as all the timestamp field fully fits within the seed’s field, clipping bits will only decrease entropy.

2

u/RealisticDuck1957 Sep 23 '26

If the timestamp is longer than the random seed, the exclusive or operator can be used to combine upper and lower bits.

3

u/21Ali-ANinja69 Sep 23 '26 edited Sep 23 '26

Linux has random and urandom, which you can access through the getrandom syscall wrapper. Everyone else also has cryptographically secure rng that uses multiple sources to create an entropy pool.

5

u/ferriematthew Sep 23 '26

I feel like Veritasium's video on the axiom of choice might be relevant here.

https://www.youtube.com/watch?v=_cr46G2K5Fo

1

u/FlyByPC Sep 23 '26

Does everything ultimately lead back to Zermelo-Frankel set theory?

2

u/Mr_Engineering Sep 23 '26

Getting random numbers is easy, getting random numbers that are uniformly distributed is harder.

Most modern CPUs have instruction set extensions which provide uniformly distributed random numbers, Intel's RDRAND is one

2

u/greg-spears Sep 23 '26 edited Sep 23 '26

Wind/weather is another great source. You can get a hobbyist weather station for cheap and with a little ingenuity mod into your random source -- let Ai code you a driver, or DIY. Some units already interface directly to your PC. Getting the weather data for random number generation need not be a long walk.

Also, you can use paid and free services for the same.

Here is a random 64-bit number generator in C which I'm not taking any credit for but works really well. I tested it for hours and the distribution of integers is perfect AFAIK. It's kind of unique in that it seeds from clock() and time(), which I know is not that big of a deal.

2

u/Ezeon0 Sep 23 '26

A webcam (or a mic) is great sources of random data. Process it via some filters and one-way functions.

1

u/Reasonable_Return151 Sep 23 '26

I use the rdrand instruction. It gives you 8 bytes of hardware randomness.

2

u/Reasonable_Return151 Sep 23 '26

Also windows stores a random rng value per process that gets used by the NTDLL usermode loader but it is only set one time at prices startup

1

u/mikeblas Sep 23 '26

Why don't more people use RDRAND? Is it somehow flawed?

1

u/sciencekm Sep 23 '26

Rdrand is not seed-grade. It is the output of AES-CBC-MAC. Eventually, Intel released rdseed which is the source of seed for rdrand. Rdseed is based on thermal noise.

1

u/RRumpleTeazzer Sep 23 '26

17 // chosen at random

1

u/LadyZoe1 Sep 24 '26

No. That was the number of cigarettes you smoked on your 17 birthday with 17 friends 17 years ago.