-2

I wan't to generate token to verify the email of users, I learn about universal hashing (selecting a hash function at random from a family of hash functions) and I wrote this code in PHP

Is it a secure method to generate token ?

$string ='';
$length = 60;
$pattern = 'abcdefghijklmnpqrstuvwxyABCDEFGHIJKLMNPQRSTUVWXY0123456789';
$hashList = array('sha256','sha384','sha512','ripemd256','ripemd320','openssl_random_pseudo_bytes');
$randNumber = mt_rand(0, 6);

for($i=0; $i<$length; $i++)
{
    $string .= $pattern[rand()%strlen($pattern)];
}

switch ($randNumber) {

    case 0:
    return substr(hash($hashList[$randNumber],$string),0,$length);    
    break;

    case 1:
    return substr(hash($hashList[$randNumber],$string),0,$length);
    break;

    case 2:
    return substr(hash($hashList[$randNumber],$string),0,$length);
    break;

    case 3:
    return substr(hash($hashList[$randNumber],$string),0,$length);
    break;

    case 4:
    return substr(hash($hashList[$randNumber],$string),0,$length);
    break;

    case 5:
    return substr(bin2hex($hashList[$randNumber]($length)),0,$length);
    break;

    default:
    return $string;
    break;

}
azro
  • 53,056
  • 7
  • 34
  • 70
  • 3
    No, never roll your own crypto. In this case you just need to use a proper random source, this should be enough `$token = bin2hex(openssl_random_pseudo_bytes(16));` – JimL Nov 05 '17 at 09:42
  • All this overkill "crypto" and the one important bit (`rand()`) makes it all vulnerable. @JimL is right, use that one line. – Gabor Lengyel Nov 05 '17 at 09:44
  • Using deterministic pseudo-random number generators is never cryptographically secure. It just creates an additional attack vector i.e. someone can predict tokens by knowing your initial seed. – apokryfos Nov 05 '17 at 09:52
  • Even `openssl_random_pseudo_bytes()` isn't always crypto-safe; use `random_bytes()`. – Narf Nov 06 '17 at 11:58

1 Answers1

0

It seems a bit complicated for me, verifying users email may not be the most important thing to secure, generating hash trough that function. It's unlikely to guess hash value.

I would choose only one hash function, don't just create hash value from username, email values, add some salt or random stuff into the string. Next option would be controlling how many invalid verifications has been processed and just block user to verify for some period.

apincik
  • 341
  • 4
  • 14