True random number generator in pure ZSH

trng() { local flips=""; while ((${#flips[@]}<256)); do local coin=0; local stop=$((EPOCHREALTIME+0.001)); while (($EPOCHREALTIME<$stop)); do ((coin^=1)); done; flips+=$coin; done; local h=($(print "$flips" | sha256sum -)); print "$h[1]"; }
Do not use this in production! This is a true hardware random number generator using your system as the entropy source. It models flipping a coin by pitting a fast clock (the CPU) against a slow clock (the RTC). The CPU models the coin flipping head over tails during flight and the RTC models the duration of the coin's flight in the air. A timer is set 1 millisecond into the future and a bit is flipped as fast as possible before the timer expires. 256 bits are collected then hashed with SHA-256 to whiten the data and ensure uniformity. This makes some assumptions however. It assumes that your system is not compromised. It assumes your system is generating enough interrupts for the kernel scheduler to be unpredictable on what gets CPU priority. It assumes that your installed sha256sum(1) command is correctly implemented. Just because you can, doesn't mean you should. Use your system's RNG (EG, /dev/urandom) instead.
Sample Output
$ trng
277def6b073f1d6d17749a203e47e35e1d0bbdda1d7a863ca561678cd456130b
$ trng
717bc9424bb93da075f996457677675b2eef01a4261cff28adb7cb9443b33ad4
$ trng
385286d0add7e763065af60ac80ee0499b7154494c9304ae14ee307bb0b0d60a

2
By: atoponce
2025-11-24 18:13:40

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: