Cap'n Steve has asked for the wisdom of the Perl Monks concerning the following question:

I'm setting up a login system and when a new user is created, I need to generate a salt to be used when hashing their password. I'm using MySQL, which can apparently store 3-byte UTF8, so should I use that or just stick to ASCII? Is there a better way to get random characters? Here's what I have so far:
my @characters; push @characters, chr(int(rand() * 16777215 + .5)) for 1..10; my $salt = join('', @characters);

Replies are listed 'Best First'.
Re: Generating random characters for a salt.
by fenLisesi (Priest) on Aug 30, 2007 at 09:59 UTC
    Due to merlyn:
    use Digest::MD5 qw(md5_hex); my $salt = md5_hex( time().{}.rand().$$ );
    Cheers.
      That's certainly interesting, but it seems strange to go to those lengths to get a random number and then limit it to a hex string. Granted, I'm not exactly a cryptography expert, but don't you want the largest possible pool of characters?
        If you are given these rules:

        1. Your salt must be N characters long or shorter
        2. N is a small integer

        then, yes, you would want a big char set. That is not the case with salts, however. Heck, you could restrict yourself to two characters and still be arbitrarily uhm... arbitrary by making the string longer.

        The incredibly-randomness and terribly-hard-to-guessness of a salt is not critical: it is going to be hashed again.

        Disclaimer: I am not a crypto expert either. /me .oO(Come to think of it, I am not an expert in anything, really. That's not very good at age 34)

        Cheers.

Re: Generating random characters for a salt.
by moritz (Cardinal) on Aug 30, 2007 at 07:11 UTC
    You should only use multibyte characters if you are sure that the underlying cryptographic system can handle them. I'm sure it can handle bytes.

    And there is a more elegant way, which is not very much different from what you do:

    my $salt = pack "C10", map { int(256*rand()) } 0..9

    If you want to stick to ASCII (2**70 is still a very large number), just change to constant to 128.

Re: Generating random characters for a salt.
by beryan (Scribe) on Aug 30, 2007 at 17:03 UTC
    If you are on a UNIX flavor system give it a try reading /dev/random it is always generating random sequences (deterministic random okay but is really useful if you do not need quantum random)
      I thought about that, but I'd like to keep it as cross-platform as possible. I know nul on Windows is the equivalent of /dev/null, but is there a random equivalent?
        No, there's no such device on Windows.