linux,

How to generate random password from the CLI

Nov 27, 2021 · 2 mins read · Post a comment
How to generate random password from the CLI

There are a lot of ways to generate random passwords, starting from simple password generator sites found online to the most advanced password management solutions. Today’s topic will be focused on creating passwords from the CLI using quick and simple methods.

Prerequisites

  • Shell environment

Solutions

openssl

Let’s start with the good old openssl.

$ openssl rand -base64 16

Example output:

BQqO0FTa9ijqPPjve+MYUA==

gpg

Alternatively, gpg or known as GnuPG is a command-line cryptographic tool and I highly recommend it.

$ gpg --gen-random --armor 1 16

Example output:

lr/snIt7ZieYx+qS9BYWXQ==

/dev/urandom

Last but not least, /dev/urandom is known as a pseudorandom number generator. /dev/random and /dev/arandom are available as well, and clearly there are some differences between them in terms of use-cases and security, but I won’t be getting into details about it.

$ tr -dc A-Za-z0-9 < /dev/urandom | head -c16; echo

Note:

  • If you are getting tr: Illegal byte sequence error, add LC_CTYPE=C in front of the command:
    LC_CTYPE=C tr -dc A-Za-z0-9 < /dev/urandom | head -c16; echo
    

Example output:

N41oKL5tDwloB7sz
  • If you want to add special characters as well, your command should look something like this:
    $ LC_CTYPE=C tr -dc 'A-Za-z0-9_!@#$%^&*()\-+=' < /dev/urandom | head -c16; echo
    

Example output:

OPK-S0Ejzi-g_6Om

Conclusion

Now, I’ve seen using the system date (date command) as an alternate method, but this is really bad, since it’s basically a weak strategy and a predicable one too. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.