What’s a secure way to generate a random password from Bash?
Asked by
radial symmetry fan
Is it possible to generate a random password from a Bash script? I'm looking for a practical command or short script that can create a password of a specified length, preferably using a cryptographically secure source of randomness.
Answers
A simple option is OpenSSL, which uses a secure random source: `openssl rand -base64 16`. Adjust the number to change the output length, though Base64 may include punctuation and padding characters.
Reply to this answer
You can read from `/dev/urandom` and keep only the characters you want. For example: `tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 16`. This produces a 16-character alphanumeric password. `/dev/urandom` is generally the appropriate device for this kind of non-blocking secure random data.
Reply to this answer
If you want an installed utility rather than writing a command yourself, `pwgen` is convenient and can generate passwords that are easier to remember. Just make sure to use its secure-random option when generating passwords for real security purposes.
Reply to this answer
A Bash loop using `$RANDOM` can produce random-looking strings, but it should not be used for security-sensitive passwords. Bash’s generator has limited internal state, so commands such as OpenSSL or `/dev/urandom` are a better choice.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions