Cryptographically secure 32-bit RNG in strict ZSH

srandom() { zmodload zsh/system; local byte; local -i rnd=0; repeat 4; do sysread -s 1 byte || return; rnd=$(( rnd << 8 | #byte )); done < /dev/urandom; print -r -- $rnd; }
ZSH ships a couple random number generators via the $RANDOM environment variable and rand48() via zsh/mathfunc, but neither are cryptographically secure. This code produces a 32-bit random number suitable for cryptography. It's only dependency is /dev/urandom and it does not rely on any shell commands or 3rd party utilities. It assumes ZSH was compiled with 64-bit integer support.
Sample Output
1018359216

1
By: atoponce
2020-12-17 13:39:17

What Others Think

Osmanthus fragrans tea is a kind of precious flower tea made from exquisite tea billet and fresh osmanthus
ruiling · 268 weeks and 5 days ago
thank you for sharing with us...
Mohitvermaji51 · 267 weeks and 3 days ago
Bitmain Antminer E9 (3Gh) For Sale Ad Description :Model Antminer E9 (3Gh) from Bitmain mining EtHash algorithm with a maximum hashrate of 3Gh/s for a power consumption of 2556W. Whatsapp : +17633085349
miners001 · 232 weeks and 3 days ago

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: