http://www.perlmonks.org?node_id=417743

I know that there are at least a few others besides me here who do the whole web applications thing. I'm pretty confident that there are also other areas of programming that require a nice randomly generated key, for whatever purpose. The question is, how should one generate these keys in a fast and efficient manner, while at the same time ensuring that it is extremely difficult to guess or compute these keys.

Methods vary from person to person of course, which is the primary reason I'm posting this to begin with. I'm interested to see which methods people use to generate keys for their applications. Everything from simple methods to the extremes. How much work isn't enough, and how much work in generating such keys is considered overdone and redundant?

Quick examples and tests follow. Notice how each of the first three examples hit repeat hashes after several thousand loops. My own code example is still running steadfast.

# CGI::Session::SHA1 # repeat session key hit at 11435 use Digest::SHA1; my $key = Digest::SHA1->new()->add( $$, time(), rand(9999) )->hexdigest(); # CGI::Session::MD5 # repeat session key hit at 10481 use Digest::MD5; my $key = Digest::MD5->new()->add( $$, time(), rand(9999) )->hexdigest(); # Apache::Session::Generate::MD5 # repeat session key hit at 4398 use Digest::MD5 qw( md5_hex ); my $key = md5_hex( md5_hex( time() . {} . rand() . $$ ) ); # My own concoction # currently at count 80699, no repeat keys yet use Digest::SHA qw( sha224_base64 ); my $key = sha224_base64( join( '', map { chr( (1..127)[rand 127] ) } 1..1000 ) );