Monday, July 2, 2007

Generate Random Passwords on the Command Line

Not too infrequently, I have the need to generate random strings on the command line, mostly for password creation. Usually, I go to a password generation site. However, this is slow, requires I have an internet connection at the time, and may be insecure as the site can record the password and my IP.

A far simpler way would be to have a script to do the generating for me. There are several such scripts for BASH floating around on the internet. But most of them are rather simple and do not let you easily select how long of a string you want. The following works nicely:

#!/bin/bash
###################################
# Created on July 2, 2007 by Samuel Huckins
# Adopted from the basic script floating
# around the internet.
#
# Generates random password. Of length equal to number given after
# command, otherwise 10.
#
# Uses /dev/urandom and not /dev/random since the latter
# can block without enough hardware entropy.
###################################
#
# Checks to see if user entered something after invocation.
# If so, use that to generate right amount of random bytes,
# and display that number.
# Only works up to 25 characters, not sure why yet.
if [ -n "$1" ] ; then
let "RANDOMTOGRAB=$1+20"
echo `head -c $RANDOMTOGRAB /dev/urandom |uuencode -m - |tail -n 2 |head -c $1`
# If they entered nothing, give them a 10 character random string.
elif [ -z "$1" ] ; then
echo `head -c 20 /dev/urandom |uuencode -m - |tail -n 2|head -c 10`
exit 0
fi
I am not sure why strings longer than 25 characters are not working just yet. Passing a larger number displays a far shorter string than requested, and one which ends in several consecutive equal signs.

I need to solve this and improve its performance, but this basic script still work nicely for most tasks.

[EDIT, 10/09/07]: I just noticed that I forgot to mention originally that you will need to install uuencode. On Ubuntu, the package for this will not be obvious, since searching for uuencode in aptitude will not turn it up. You need to install sharutils. This includes uudecode and a few others in addition.

1 Comments:

Anonymous Simon said...

The length limit is down to uuencode which produces output like :
mgHZWDhtXSgIh6JR0Jh45Z0t/GRS2z52keGQIbT2NnpBGUF8IEcvEnczh/St
yFCO3yxO2UbpZ39dwFoFRiIbskU6AXPkSskcB9fjYsqRhOVjxeo2CsOtkwtz
qlOoXXd82BnuGsbgm4ho60lG1+7AZoU/DMJ3rilMTebYHw==
====
so when your take the next to last line you get some number of characters less than 60. My first though was that it might have been line breaks in the initial random string so switched to using 'dd'.

My script ended up like :
echo `dd if=/dev/urandom bs=1k count=1 2>/dev/null | tr -dc '0-9a-zA-Z' | head -c ${pw_len}`

I simply took a fairly long input string, and deleted all the non-alphanumeric characters in it using 'tr'.

July 16, 2007 at 1:46 AM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home