简体   繁体   English

PHP crypt()函数VS。 hash()函数

[英]PHP crypt() function VS. hash() function

i'm creating a login system in PHP, and i'm experiencing with hashing. 我正在用PHP创建登录系统,并且遇到了哈希。

Can someone tell me why if I use hash() with sha512 it generates a string of 128 chars while using crypt() with sha512 it is only 118 chars (but only 103 chars of hash) ? 有人可以告诉我为什么如果我将hash()与sha512一起使用时会生成128个字符的字符串,而将crypt()与sha512一起使用时却只有118个字符(但哈希仅103个字符)吗?

Example: 例:

$password = "password";
$hashed =   crypt($password, '$6$rounds=5000$'.core::genSalt().'$');
$hashed2 =  hash('sha512', $password);

echo "pwd hashed with hash() -> $hashed<br>";
echo "hashed pwd length? ".strlen($hashed);
echo "<br>-----<br>";
echo "pwd hashed with crypt() -> $hashed2<br>";
echo "hashed pwd length? ".strlen($hashed2);

and it results in: 结果是:

pwd hashed with crypt() -> $6$rounds=5000$HGWYWN+gVBLsotI5$sxqlewzU4pn4Z0/.5DlX6orE9Mw2W0Z7VJ6Qp8cCQdDqGvCJHqgiG6fYQjI2dSm78ErfXQ8QbMjq1JCVl2Hah0 
hashed pwd length? 118

pwd hashed with hash() -> b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86 
hashed pwd length? 128

Thank you 谢谢

hash() uses an hexadecimal representation([a-f0-9]) whereas crypt() seems to use [a-zA-Z0-9./] from what I see. hash()使用十六进制表示形式([a-f0-9]),而从我所见,crypt()似乎使用[a-zA-Z0-9./]。

For the hexadecimal representation, each character holds 4(16 needs 4 binary digits) bits of information, and for the crypt one, each character holds 6(64 needs 6 binary digits). 对于十六进制表示,每个字符保存4(16个需要4个二进制数字)信息位,对于crypt表示,每个字符保存6(64个需要6个二进制数字)信息。

We know that SHA-512 generates a 512 bit hash, so: 我们知道SHA-512会生成512位哈希,因此:

  • hash(): 512 / 4 = 128 characters hash():512/4 = 128个字符
  • crypt(): 512 / 6 = 85,33 ~= 86 characters, which matches with the character length if we strip the crypt mode, rounds, and salt($6$rounds=5000$HGWYWN+gVBLsotI5$). crypt():512/6 = 85,33〜= 86个字符,如果我们去除crypt模式,舍入和盐值($ 6 $ rounds = 5000 $ HGWYWN + gVBLsotI5 $),则与字符长度匹配。 In your example that's "sxqlewzU4pn4Z0/.5DlX6orE9Mw2W0Z7VJ6Qp8cCQdDqGvCJHqgiG6fYQjI2dSm78ErfXQ8QbMjq1JCVl2Hah0" 在您的示例中是“ sxqlewzU4pn4Z0 / .5DlX6orE9Mw2W0Z7VJ6Qp8cCQdDqgvCJHqgiG6fYQjI2dSm78ErfXQ8QbMjq1JCVl2Hah0”

As an illustration, see what happens when we use 10, 16 or 36 characters to represent a number. 举例说明,看看使用10、16或36个字符表示数字时会发生什么。

$decimalNumber = 123456789;
var_dump(base_convert($decimalNumber, 10, 16), base_convert($decimalNumber, 10, 36));

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

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