PHP SHA1 给出的结果与预期不同
这真的让我感到惊讶 - 这应该相当简单,但我不明白有什么区别。
我有这个函数来生成盐:
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;
}
非常基本(?)
并尝试从中创建 SHA1 哈希,给了我一个与我期望的不同的结果:
$salt = $this->_generateSalt();
$password = $salt.$password;
echo sha1($password);
$password 是由用户输入生成的字符串。 回显的哈希字符串是错误的。我不知道为什么。
var_dump($password);
在添加盐后给出了预期的字符串大小 - 将结果复制并粘贴到在线 SHA1 服务或通过 MySQL CLI 对字符串进行哈希处理给出了正确的结果。就像 $password 变量中有一些看不见的东西我不想散列。但我怎样才能找出为什么会发生这种情况呢? var_dump()、trim() 和比较结果没有让我有任何收获?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
去掉所有非字母数字特殊字符 - 据我所知,这个字符甚至不是 ASCII:¤。因此,如果您在以不同编码编码的字符串下运行 sha1,可能会弄乱事情。
(这个答案是从评论中复制粘贴的,并由于提问者的要求而添加为答案,因为它似乎解决了问题)
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:
这行不应该是:
$salt .= $characterList{mt_rand(0,strlen($characterList)-1)};
如下所示:
$salt .= $characterList[mt_rand(0,strlen($characterList) )-1)];
Shouldn't this line:
$salt .= $characterList{mt_rand(0,strlen($characterList)-1)};
Look like this:
$salt .= $characterList[mt_rand(0,strlen($characterList)-1)];