Add gen-secret: generate bash/YAML/JSON-safe random strings

Outputs cryptographically random strings using only characters safe
for unquoted use in bash, YAML, and JSON: [A-Za-z0-9._+\-:@^~]

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Paul O'Reilly
2026-03-27 11:32:55 +13:00
parent 161c633b42
commit 8bd4c7253b
3 changed files with 265 additions and 0 deletions

63
scripts/gen-secret Executable file
View File

@@ -0,0 +1,63 @@
#!/usr/bin/env bash
set -uo pipefail
CHARSET='A-Za-z0-9._+\-:@^~'
DEFAULT_LENGTH=32
usage() {
cat <<'EOF'
Usage: gen-secret [OPTIONS] [LENGTH]
Generate a cryptographically random string safe for bash, YAML, and JSON.
Arguments:
LENGTH Number of characters (default: 32)
Options:
-n, --dryrun Preview what would happen
-h, --help Show this help
EOF
}
dryrun=false
length=""
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help)
usage
exit 0
;;
-n|--dryrun)
dryrun=true
shift
;;
-*)
echo "Error: Unknown option: $1" >&2
exit 1
;;
*)
if [[ -n "$length" ]]; then
echo "Error: Too many arguments" >&2
exit 1
fi
length="$1"
shift
;;
esac
done
length="${length:-$DEFAULT_LENGTH}"
if ! [[ "$length" =~ ^[0-9]+$ ]] || [[ "$length" -le 0 ]]; then
echo "Error: Length must be a positive integer" >&2
exit 1
fi
if $dryrun; then
echo "[dryrun] Would generate a ${length}-character secret from charset: [${CHARSET}]"
exit 0
fi
tr -dc "$CHARSET" < /dev/urandom | head -c "$length"
echo