Random Password Generator

Have you ever needed bunch of strong passwords to be generated on the fly? I sometimes need to generate bunch of one use, give it to a user who will then change it and throw it away passwords. Simplest method to get good randomness is to use /dev/random. Try doing this:

Szaman2@grendel ~
$ head -n 1 /dev/random

Of course /dev/random gives you bunch of garbage, but it is a fairly random garbage. As far as I know the output of /dev/random can possibly be broken, if the system haven’t gathered enough entropy to generate truly random output. But for our purposes this is good enough. We just need to turn it into something that can be used as a password – hence all the funny ASCII marks, and control characters need to go:

Szaman2@grendel ~
$ head -c 6 /dev/random | uuencode -m -
begin-base64 644 -

Ah, we are getting warmer. Instead of a whole line I’m just grabbing 6 first characters. Uuencode converts all the garbage to readable ASCII. Unfortunately it produces the garbage above and below the actual randomized output. You can pick out the line in many ways. I decided to use sed:

Szaman2@grendel ~
$ head -c 6 /dev/random | uuencode -m - | sed -n '2p'

Tada! Only problem with this solution is that the script can still generate strings that include non alphanumeric characters such as /, +. ? or _. Some systems do not allow this type of passwords. This should not be a problem. Since I’m already using sed, I can easily include some regexp there to fix this:

Szaman2@grendel ~
$ head -c 6 /dev/random | uuencode -m - | sed -n '2s/[^a-zA-Z 0-9]//;2p'

So, here you have it. A randomized password generator that can be nicely fit into a shell script or a batch job.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: