AzLearn

تمرين إعادة البناء

Password Generator

أعد كتابة مولد كلمات مرور بسيط في Bash باستخدام RANDOM وتحقق من الطول.

bash ~12 دقيقة متوسط
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
#!/usr/bin/env bash
# Cryptographically secure password generator.
# Reads bytes from /dev/urandom rather than $RANDOM (a non-crypto LCG PRNG).
# Portable to Bash 3.2+ (macOS default) — uses no associative arrays or new builtins.
set -euo pipefail

length="${1:-16}"

if [[ ! "$length" =~ ^[0-9]+$ ]] || ((length < 4 || length > 64)); then
	printf 'Length must be a number between 4 and 64.\n' >&2
	exit 1
fi

# LC_ALL=C makes `tr` byte-oriented, so multi-byte UTF-8 sequences in
# /dev/urandom won't be interpreted as characters and silently dropped.
LC_ALL=C tr -dc 'A-Za-z0-9!@#$%^&*' </dev/urandom | head -c "$length"
printf '\n'
اكتب هنا