Reputation: 21
I have extremely annoying issues with the php hash() function. For some strings the returned hash is just an empty string, for others it works fine.
I wrote the following:
$new_salted_pw = $salt.$pepper.$new_pw;
echo $new_salted_pw."... ";
$hash = hash("sha256", $new_salted_pw);
if($hash>120)
$hash = substr($hash, 120);
echo $hash;
I used the passwords geheim23
and Geheim23
for testing, so only 1 character difference.
The result is:
k0g3po32ggd0sv8oehgklbp2bd8eddxXMaxGTPJSQZSAJzgZSgaZxvUfGeheim23... d79e2044baa8a0a7363c88b4a2224277ac883eabc22cd28d61c1cdc31bb1c3fc
k0g3po32ggd0sv8oehgklbp2bd8eddxXMaxGTPJSQZSAJzgZSgaZxvUfgeheim23...
No hash for the second one. It's empty. Same code, no result.
Even more interestingly, hashing geheim23
in exactly the same way works in a different part of my script without problems.
And that's when I decided to ask Stackoverflow if it knows why PHP is doing this to me, how to fix it, or what function I could use instead of hash().
Thank you.
Upvotes: 1
Views: 1166
Reputation: 1
You should use password_hash() and password_verify() for hashing/verifying passwords.
These functions are available in PHP > 5.5 but I don't know any reason why anyone should do a new project for older version.
Some point why you should use that:
Upvotes: 0
Reputation: 59681
The problem is not with the hash()
function! The problem is in the substr()
function. You have to change this:
(Here you started at the position 120, but you want the string form 0 to 120)
$hash = substr($hash, 120);
to:
$hash = substr($hash,0, 120);
Also i think you want to check if the length is longer that 120 and not if the hash value is bigger than 120 so change this:
if($hash>120)
to this:
if(strlen($hash) > 120)
For more information about substr()
see the manual: http://php.net/manual/en/function.substr.php
And a quote from there:
string substr ( string $string , int $start [, int $length ] )
Upvotes: 2