BASH
Generate Random Secure Passwords/API Keys
Learn to generate strong, random passwords or API keys using `/dev/urandom` and `base64` in Bash, ideal for secure application configuration.
#!/bin/bash
# Configuration
LENGTH=${1:-16} # Default length is 16 if not provided as argument
# Method 1: Using /dev/urandom and tr
# Reads random bytes, translates non-printable chars to a specified character set
# head -c $LENGTH: takes the first N characters
echo "Generated Password (Method 1 - Alphanumeric+Special):"
PASSWORD_M1=$(cat /dev/urandom | tr -dc 'A-Za-z0-9_@#$%^&*-+=' | head -c ${LENGTH})
echo "$PASSWORD_M1"
echo "
Generated API Key (Method 2 - Base64 encoded):"
# Method 2: Using /dev/urandom and base64
# Generates N random bytes, then base64 encodes them
# This often results in a more uniformly random distribution across the base64 alphabet
API_KEY_M2=$(head /dev/urandom | tr -dc A-Za-z0-9_@#$%^&*-+= | head -c $((LENGTH))) # Using a similar method as M1 for consistency with character set
# Alternatively for pure base64: API_KEY_M2=$(head /dev/urandom | base64 | head -c ${LENGTH})
echo "$API_KEY_M2"
How it works: This Bash script offers two methods to generate strong, random strings suitable for passwords or API keys. Method 1 reads bytes from `/dev/urandom`, filters them through `tr` to select a desired character set (alphanumeric and special characters), and then uses `head -c` to truncate to the specified length. Method 2, though shown with a similar character filtering, could alternatively use `base64` encoding on `/dev/urandom` output, which is robust for API keys due to its wide character distribution. The script defaults to a length of 16 characters but can be customized by passing an argument.