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 ) );

In reply to session keys: how far to take it by saskaqueer

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.