Debian Codegraph @

examples/kubernetes/token_generation.sh

raw
1 #!/usr/bin/env bash
2
3 # https://github.com/kubernetes/kubernetes/blob/84beab6f26609527752ff441c155813b783fe145/cluster/gce/gci/configure-helper.sh#L44
4 # secure_random generates a secure random string of bytes. This function accepts
5 # a number of secure bytes desired and returns a base64 encoded string with at
6 # least the requested entropy. Rather than directly reading from /dev/urandom,
7 # we use uuidgen which calls getrandom(2). getrandom(2) verifies that the
8 # entropy pool has been initialized sufficiently for the desired operation
9 # before reading from /dev/urandom.
10 #
11 # ARGS:
12 # #1: number of secure bytes to generate. We round up to the nearest factor of 32.
13 function secure_random {
14 local infobytes="${1}"
15 if ((infobytes <= 0)); then
16 echo "Invalid argument to secure_random: infobytes='${infobytes}'" 1>&2
17 return 1
18 fi
19
20 local out=""
21 for (( i = 0; i < "${infobytes}"; i += 32 )); do
22 # uuids have 122 random bits, sha256 sums have 256 bits, so concatenate
23 # three uuids and take their sum. The sum is encoded in ASCII hex, hence the
24 # 64 character cut.
25 out+="$(
26 (
27 uuidgen --random;
28 uuidgen --random;
29 uuidgen --random;
30 ) | sha256sum \
31 | head -c 64
32 )";
33 done
34 # Finally, convert the ASCII hex to base64 to increase the density.
35 echo -n "${out}" | xxd -r -p | base64 -w 0
36 }
37
38 secure_random $1