Skip to content

Instantly share code, notes, and snippets.

@jhunterkohler
Last active July 31, 2021 02:38
Show Gist options
  • Save jhunterkohler/7f91519ddabafb7488da5ec326ae2fbb to your computer and use it in GitHub Desktop.
Save jhunterkohler/7f91519ddabafb7488da5ec326ae2fbb to your computer and use it in GitHub Desktop.
simple bash script for generating random bytes
#!/usr/bin/env bash
read -r -d '' usage <<EOF
Usage:
random [options] bytes
random -h|--help
Generate random bytes from /dev/random.
Options:
-h, --help
print help
EOF
error() {
printf >&2 "Error: %s\n\n%s\n" "$*" "$usage"
}
main() {
if (($# != 1)); then
error "Incorrect number of argument"
elif [[ $1 =~ (-h|--help) ]]; then
printf "%s\n" "$usage"
elif [[ $1 =~ ^[0-9]+$ ]]; then
local bytes=""
while ((${#bytes} < $1)); do
bytes+=$(head --bytes $(($1 - ${#bytes})) /dev/random |
tr --complement --delete 'a-zA-Z0-9~!@#$%^&*_-')
done
printf "%s" "${bytes:0:$1}"
else
error "'bytes' must be a non-negative integral value"
fi
}
main "$@"
@jhunterkohler
Copy link
Author

jhunterkohler commented Jul 31, 2021

PSA

Not cryptographically secure. But if I had to tell you that, then you're most certainly in the wrong place

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment