BASH

Generate Cryptographically Secure Random Passwords

Learn to generate strong, random, and cryptographically secure passwords or strings directly from your Bash terminal using system entropy sources.

#!/bin/bash

# --- Configuration ---
LENGTH=${1:-16} # Default password length is 16, or use the first argument
# Define the character set to use for the password. Avoid ambiguous chars if possible.
# Alphanumeric + common symbols
CHAR_SET='A-Za-z0-9!@#$%^&*()_+-='
# ---------------------

# Check for required commands and /dev/urandom
if ! command -v head &> /dev/null || ! command -v tr &> /dev/null || [ ! -c /dev/urandom ]; then
    echo "Error: Required commands (head, tr) or /dev/urandom not found." >&2
    echo "Please ensure core utilities are installed and /dev/urandom exists." >&2
    exit 1
fi

# Validate LENGTH is a positive integer
if ! [[ "$LENGTH" =~ ^[1-9][0-9]*$ ]]; then
    echo "Error: Invalid password length specified. Must be a positive integer." >&2
    echo "Usage: $0 [length]" >&2
    exit 1
fi

# Generate a random string using /dev/urandom
# 1. head /dev/urandom: Reads random bytes from the kernel's entropy pool.
# 2. tr -dc '$CHAR_SET': Deletes (d) all characters NOT (c) in the defined character set.
# 3. head -c "$LENGTH": Takes exactly the specified number of characters from the filtered stream.
PASSWORD=$(head /dev/urandom | tr -dc "$CHAR_SET" | head -c "$LENGTH")

if [ -z "$PASSWORD" ]; then
    echo "Error: Failed to generate password. Output was empty." >&2
    exit 1
fi

echo "Generated Password: $PASSWORD"

exit 0
How it works: This Bash script generates strong, cryptographically secure random passwords. It takes an optional argument for the desired password length, defaulting to 16 characters. The core logic involves reading random bytes from `/dev/urandom` (a source of high-quality entropy from the operating system). These bytes are then piped to `tr -dc` to filter and keep only characters from a predefined `CHAR_SET` (alphanumeric and common symbols). Finally, `head -c` truncates the output to the exact desired length, ensuring a password of the specified size. The script includes checks for required utilities and valid length input.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs