How to generate 256-bit random hex strings in MacOS

The command openssl gives us everything we need.

If you run openssl rand -hex 32 you will have an output like this:

openssl rand -hex 32
fe2b27f8d12cc51729c6fcf43c8316b156eb86d539330ab8eb9b5641a5569df0

But what happens if we need more than one, say 20. We'll need to run seq 20 | xargs -n1 -I{} openssl rand -hex 32 to have an output like this:

seq 20 | xargs -n1 -I{} openssl rand -hex 32
217dedf40dc5548f81cd4286c958a7344ee94cd06358f425344855b168ab352b
35adde609eaab3e49413101e21383c576b074dea7cbd9ca1bb96280534a2cfbf
23154b7b93b418c277e9956cf55e8b6fa12071da635a2ebc5c1b227f8cd62110
4089d92d6aab1554aaf0b820fb98948af723db3fc78ce4762d0e42c77a7c4571
00d76a7b63cc19952101ec60889659384dac064f60f6703f1c6ff2f84b410e8c
e6eafd79abfcba33098bba60764082b2967d7ee72c60ea86251388b4028b63eb
f6a35f27766a6879909b3af219f67898ea8a78daea9f95eceaa0cff333f79aa2
0148bfe14142b3e6922b1b525fedf742e0d11f688f319c554b06d9cfa7aa42be
787a364cd7d375109bd3a367e7237fa4b27a5defc34ffe339d0dc1da3f8bbcef
14fcbad722a9aa5215c621ebc1f42f4acbe2e30ab1f8b6f82ed97d085e1901b9
40f9cd1522084fc754901b0c61ad0636599e77ba5ea0cc216a4893fd5f7aef65
bd5394b9ae074829d0b4c724e631407d77c2c0f21a7800f44993768f5dabd37a
f36464b5efe330c2a218099d8c0c432f8ce574fc974ec51931e33c42b1448964
a8786c8250253d887c721f6373c820d648c5632e15913ea8f796dea2a6795b55
34afe950cd05e3e5df5d879617506ad37892bdface87f0340d745324813cda21
018594e77c1df0f86c5f62e4a346ecba34b6a1cef6addb91baacefc707305f84
ce7b7875d455f963a1395b0364c4e598721a33430a6ae83358d1a0767747cff9
104ced8f7b6560977873fe31368acb0aa42c0774d63735a86da9e72ff8cfd280
10758d9fd734634b83d432fd56c7bbc2ac64c4a22f13913542bcab739a4c16ee
7873867ffcabe023552b6831887acd236f5d5c8f2d65c926b5224f6a661c1930

Breakdown of the command:

Here’s what each piece does:

seq 5                   # (1) Generate the numbers 1 through 5, one per line
|                       # (2) Pipe that list into xargs
xargs                   # (3) Read input lines and build command invocations
  -n1                   #    "-n1": use one input argument per command run
  -I{}                  #    "-I{}": define “{}” as a placeholder for the input
  openssl rand -hex 32  # (4) The command to run—with {} replaced by each input
  1. seq 5 prints:
1
2
3
4
5
  1. | pipes that list into the next program.
  2. xargs -n1 -I{}:
    • -n1 tells xargs to take exactly one argument from its stdin each time it runs the command.
    • -I{} tells it "wherever you see {} in the command, substitute the argument."
  3. openssl rand -hex 32 is the command that gets run once for each input line. Because we haven’t actually placed {} in the command, it simply ignores the placeholder—but thanks to -n1 and -I{}, it still runs exactly twenty times (or N times), producing twenty independent 256-bit hex strings.