Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to generate a random string?

I would like to generate a random string (e.g. passwords, user names, etc.). It should be possible to specify the needed length (e.g. 13 chars).

What tools can I use?

(For security and privacy reasons, it is preferable that strings are generated off-line, as opposed to online on a website.)
by

2 Answers

akshay1995
My favorite way to do it is by using /dev/urandom together with tr to delete unwanted characters. For instance, to get only digits and letters:

tr -dc A-Za-z0-9 </dev/urandom | head -c 13 ; echo ''

Alternatively, to include more characters from the OWASP password special characters list:

tr -dc 'A-Za-z0-9!"#$%&'\''()+,-./:;<=>?@[\]^_`{|}~' </dev/urandom | head -c 13 ; echo

If you have some problems with tr complaining about the input, try adding LC_ALL=C like this:

LC_ALL=C tr -dc 'A-Za-z0-9!"#$%&'\''()
+,-./:;<=>?@[\]^_`{|}~' </dev/urandom | head -c 13 ; echo
pankajshivnani123
I am using the openssl command, the swiss army knife of cryptography.
openssl rand -base64 12


or
openssl rand -hex 12

Login / Signup to Answer the Question.