-3

I am trying to randomize a number with 32 hexadecimal digits in bash with seed which depends on the date.
I thought about something like: RANDOM=$(date +%N | cut -b4-9) , but it's not give me 32 hexadecimal digits.

ideas?

Software_t
  • 576
  • 1
  • 4
  • 13
  • Which `date` do you use, GNU or FreeBSD(macOS uses)? – Constantin Hong Nov 28 '22 at 17:37
  • @ConstantinHong I just run the above command in bash. – Software_t Nov 28 '22 at 17:39
  • 2
    `date +%N | md5sum | cut -c1-32`, though its randomness is debatable. – M. Nejat Aydin Nov 28 '22 at 17:39
  • @M.NejatAydin what is the purpose of `md5sum` in your command? – Software_t Nov 28 '22 at 17:40
  • @Software_t md5sum is a 128-bit hash, thus 32 hexadecimal digits. – M. Nejat Aydin Nov 28 '22 at 17:42
  • @M.NejatAydin Are you tried it? i don't get it as 32 hexadecimal digits .. – Software_t Nov 28 '22 at 18:20
  • `RANDOM` is an OS variable that generates a somewhat-random 16-bit number ... nowhere near enough to generate a 32-digit hex value – markp-fuso Nov 28 '22 at 18:24
  • why the requirement to use a date (nanoseconds) as a seed? are you actually going to save the `date +%N` output for later use (eg, to reseed `RANDOM`)? – markp-fuso Nov 28 '22 at 18:31
  • 1
    Does this answer your question? [How to get a random string of 32 hexadecimal digits through command line?](https://stackoverflow.com/questions/34328759) or [Shell script to generate random hex numbers](https://stackoverflow.com/q/40277918) – markp-fuso Nov 28 '22 at 18:35
  • 2
    @Software_t Sure, I've tried it. You must certainly get a 32-xdigit number (tough its randomness is debatable). – M. Nejat Aydin Nov 28 '22 at 18:47
  • 2
    Why are you specifically using date as seed? Is that *necessary*? It's seed only, so isn't it better to just assure you have sufficiently random data? – Paul Hodges Nov 28 '22 at 19:20
  • Attempting to override the built-in variable `RANDOM` is separately an error. You won't get back the value you assigned. Perhaps see also [Correct Bash and shell script variable capitalization](https://stackoverflow.com/questions/673055/correct-bash-and-shell-script-variable-capitalization) – tripleee Nov 29 '22 at 07:23

3 Answers3

0

I'm always generating with: openssl rand -base64 32

0

Feed /dev/urandom to tr and delete all but hex digits:

$ tr -dc '[:xdigit:]' < /dev/urandom | head -c32
90D75De9CaA0C38a15B8facf59CBBDdc

If you need all upper (or all lower):

$ tr -dc '0-9A-F' < /dev/urandom | head -c32
CBABC737B0F9C059531CA7672FCA52F6

$ tr -dc '0-9a-f' < /dev/urandom | head -c32
87fa3f2e4f98a8e8eecb8236e2736eba
markp-fuso
  • 28,790
  • 4
  • 16
  • 36
0

Eliminate your need for the date.
If it's an assignment, say so.

Assuming it is -

$: src="0123456789ABCDEF" && RANDOM=$(( $(date +%s) % 32767 ))    &&
>  for c in {1..32}; do printf "%s" ${src:$((RANDOM%16)):1}; done &&
>  echo 
14E4552562D03BB6FCAC8602B0D38BE7
Paul Hodges
  • 13,382
  • 1
  • 17
  • 36