Last active
March 12, 2025 21:25
-
-
Save consideRatio/1c42cc9f07a7545cb81ec98219629f15 to your computer and use it in GitHub Desktop.
Helm helper template randHex to generate random hexadecimal (hex, base16) numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{/* | |
Returns given number of random Hex characters. | |
In practice, it generates up to 100 randAlphaNum strings | |
that are filtered from non-hex characters and augmented | |
to the resulting string that is finally trimmed down. | |
*/}} | |
{{- define "jupyterhub.randHex" -}} | |
{{- $result := "" }} | |
{{- range $i := until 100 }} | |
{{- if lt (len $result) . }} | |
{{- $rand_list := randAlphaNum . | splitList "" -}} | |
{{- $reduced_list := without $rand_list "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" }} | |
{{- $rand_string := join "" $reduced_list }} | |
{{- $result = print $result $rand_string -}} | |
{{- end }} | |
{{- end }} | |
{{- $result | trunc . }} | |
{{- end }} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@gjorando: This is not optimal, because randAscii does not generate all possible bytes from 0x00 to 0xFF, so the result has lower entropy than the other solutions mentioned here.
28 random hex digits can be easily generated using
{{ regexReplaceAll "-." uuidv4 "" }}
. This removes digits directly following a hyphen, because some of them have reduced entropy (constant 4, or 8 to b). This can be embedded in a loop to produce more than 28 digits. The end result can be cut to a specific length withsubstr
.