Search code examples
phppassword-hash

crypt() function not giving proper hashes


I have made an password hashing script using this and this, i am getting it to work correctly except some times the crypt function is giving hash as "*0", and then it fails.

PHP Codes

    $password='password';
    $salt = '$2y$07$';
    $salt .= base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_RANDOM));
    $salt .='$$';
    $password_hash = crypt($password, $salt)';

    echo $password_hash.'<br />';

Using above i am getting values as

    $salt = '$2y$07$8K3i8rJ7n7bsJA36CfbabQ==$$';
    $crypt_password = $password_hash;
    $crypt_password = '$2y$07$8K3i8rJ7n7bsJA36CfbabO9ojj2hl61azl8CubJQhRTgla4ICiCVC';
    if (crypt($password,$crypt_password)===$crypt_password)
    {
    echo 'password verified';
    }
    else{
    echo 'password NOT verified';
    }

Please see and suggest any possible way to make it work correctly.

Thanks.


Solution

  • The problem is that base64_encode may generate a string with '+' symbol, which is considered an incorrect salt by crypt function.

    var_dump your $salt along with $password, and you'll see that each time + character is used in the salt, crypt function will return a '*0' string - the sign of failure.

    One possible way of solving it is replacing all '+' signs with '.':

    $salt = str_replace('+', '.', $salt);