简体   繁体   English

PHP SHA1提供的结果与预期不同

[英]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: 尝试从中创建一个SHA1哈希,给了我不同的结果:

$salt = $this->_generateSalt();
$password = $salt.$password;
echo sha1($password);

$password is a string generated by user input. $ password是由用户输入生成的字符串。 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. 在添加盐之后,可以得到预期的字符串大小-将结果复制并粘贴到在线SHA1服务中,或者通过MySQL CLI对字符串进行哈希处理即可得到正确的结果。 It's like there's something invisible in the $password variable I wan't to hash. 就像$ password变量中有不可见的东西,我不想散列。 But how can I find out why this is happening? 但是,我怎么才能知道为什么会这样呢? var_dump(), trim() and comparing results haven't gotten me anywhere? var_dump(),trim()和比较结果还没让我明白吗?

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 ) );

Get rid of all the non alpha-numeric special characters - this one is even not ASCII as far as I can tell: ¤. 除去所有非字母数字的特殊字符-就我所知,这个字符甚至不是ASCII:¤。 So it might mess things up if you run sha1 under string encoded in different encodings. 因此,如果在以不同编码编码的字符串下运行sha1,可能会搞砸。

(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) (此答案是复制自注释的副本,并由于要求者的要求而添加为答案,因为它似乎可以解决问题)

Shouldn't this line: $salt .= $characterList{mt_rand(0,strlen($characterList)-1)}; 这行不应该这样: $salt .= $characterList{mt_rand(0,strlen($characterList)-1)};

Look like this: $salt .= $characterList[mt_rand(0,strlen($characterList)-1)]; 看起来像这样: $salt .= $characterList[mt_rand(0,strlen($characterList)-1)];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM