Brian
Brian

Reputation: 4418

Does hashing random data for tokens increase security?

I use phpass for generating random salts and password hashing but my question is for things like a password reset I create a unique token. Basically I grab 16 bytes of random data and then pass it through a sha256 hash. Is this a good practice or should I just stick to using the 16 bytes of data

private static function get_random_bytes($count) {
    $output = '';
    if (is_readable('/dev/urandom') &&
            ($fh = @fopen('/dev/urandom', 'rb'))) {
        $output = fread($fh, $count);
        fclose($fh);
    }

    $random_state = microtime();
    if (function_exists('getmypid'))
        $random_state .= getmypid();

    if (strlen($output) < $count) {
        $output = '';
        for ($i = 0; $i < $count; $i += 16) {
            $random_state =
                    md5(microtime() . $random_state);
            $output .=
                    pack('H*', md5($random_state));
        }
        $output = substr($output, 0, $count);
    }

    return $output;
}

Upvotes: 2

Views: 502

Answers (2)

Ragamffn
Ragamffn

Reputation: 319

Yes, hashing random data for password reset tokens absolutely increases security.

A scenario in which non-hashed tokens can help compromise an account:

Attacker

  1. gets read access to your database,
  2. waits for token to appear in password reset tokens table <g>,
  3. takes token, associated email address, and crafts URL

    http://example.com/password_reset?t=gobble-dee-goo-token

  4. now can change password for associated email address.

Through phpass hashing, even if an attacker gets read access to your DB, a password reset function can't be used to compromise an account. This is because they can't use the hash of the token to craft the URL.

Upvotes: -1

regality
regality

Reputation: 6554

If the random data is cryptographically strong, which it should be, then no you don't need to hash it.

If your data is not crypto-strong, such as values retrieved with rand() then hashing may be slightly more secure, but the benefit is minimal and you should really just use a stronger PRNG.

In this case, the only security flaw possible is if someone

  1. used sql injection to pull all the passwords and salts from the database,
  2. Found a pattern in the salt generation,
  3. Made a rainbow table based on predicted salts,
  4. Get the data from your database again,
  5. Use the rainbow table to crack large numbers of passwords from the database.

So basically, no, it does not add security. Furthermore the code you have above uses /dev/urandom, which provides very strong randomness, so the benefit is even further diminished as step 2 listed above is more or less impossible. The only organizations that are under that heavy fire are the NSA, CIA, and similar groups.

Upvotes: 3

Related Questions