By fernando | February 4, 2009

Generating random salts from bash

From the ‘just because it can be done’ column, here comes a handy shell script to generate random salts.

So, without further ado,  here it goes:

#!/bin/bash 

[ $# -eq 0 ] && {
        echo "usage: salt <length>">&2
        exit
}
strings </dev/urandom | while read line; do
        echo $line | tr '\n\t ' $RANDOM:0:1 >> /tmp/.salt.$$
        salt=$(cat /tmp/.salt.$$)
        [ ${#salt} -ge $1 ] && salt=${salt:0:$1} && echo $salt && break
done
rm -f /tmp/.salt.$$

I had to use $1 and not a var, and echo the salt right from inside the while, because the ‘|’ creates another shell, so I can’t pass variables to or from the while in this case.

If you want to keep things simple, you can go perl and just do

#!/usr/bin/perl
use Crypt::Salt;
my $length = shift;
print salt($length);

But if you ever find yourself in a server with no cpan, the first option might prove useful :)

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • MisterWong
  • Y!GG
  • Webnews
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • email
  • Facebook
  • LinkedIn
  • Technorati

Related posts:

  1. Generating data with dbmonster In my last post I included some sample data...
  2. Running commands from the shell with a timeout Sometimes, in a shell script, you need to run a...
  3. Intrusion detection at the application level, for PHP Here’s phpids, an Intrusion Detection System for PHP. According to...
  4. Running commands from the shell with a timeout (pt 2) Here’s an improved version of the safecmd script. This one...

Related posts brought to you by Yet Another Related Posts Plugin.

Topics: Programming | Comments Off

Comments are closed.