PHP SHA1 gives different result than expected
This really surprises me - this should be rather simple, but I can't figure out what the difference is.
I have this function to generate a salt:
private function _generateSalt($max = 128)
{
$characterList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#¤%&/()~";
$i = 0;
$salt = "";
do {
$salt .= $characterList{mt_rand(0,strlen($characterList)-1)};
$i++;
} while ($i < $max);
return $salt;
}
Pretty basic(?)
And trying to create a SHA1 hash from this, gives me a different result what I would expect:
$salt = $this->_generateSalt();
$password = $salt.$password;
echo sha1($password);
$password is a string generated by user input. The echoed hashed string is wrong. And I don't know why.
var_dump($password);
after prepending the salt gives me the expected string size - copy and paste the result to an online SHA1 service or hashing the string开发者_开发百科 through MySQL CLI gives the correct result. It's like there's something invisible in the $password variable I wan't to hash. But how can I find out why this is happening? var_dump(), trim() and comparing results haven't gotten me anywhere?
Get rid of all the non alpha-numeric special characters - this one is even not ASCII as far as I can tell: ¤. So it might mess things up if you run sha1 under string encoded in different encodings.
(This answer is copy pasted from the comments and added as an answer because of the asker's request as it seem to fix the problem)
A better way to generate a salt would be:
// True for cryptographically strong, FALSE otherwise
$salt_strong = TRUE;
// The length
$salt_length = 32;
// Create the salt and load the results into a local var
$salt = bin2hex( openssl_random_pseudo_bytes( $salt_length , $salt_strong ) );
Shouldn't this line:
$salt .= $characterList{mt_rand(0,strlen($characterList)-1)};
Look like this: $salt .= $characterList[mt_rand(0,strlen($characterList)-1)];
精彩评论