2013-12-17 34 views
1

一个快速而肮脏的实验。PHP crypt问题

我把这段代码放到一个.php文件中,并从我的虚拟主机上加载它。

结果是“It works!”但为什么?它应该失败了吗?我是从这里以下示例#1:http://php.net/manual/en/function.crypt.php

<?php 
$pass1 = "thetimeshallwhintercows"; 
$salt = "temperpedic"; 

$crypt_pass = crypt($pass1, $salt); 

if($crypt_pass == crypt("thetimeshallwhintercowz", $crypt_pass)) 
{ 
    print("It works!<br/>"); 
    print($crypt_pass ); 
    print("<br/>"); 
    print(crypt("thetimeshallwhintercowz", $crypt_pass)); 
} 
else 
{ 
    print("try again...."); 
} 

?> 
+0

示例#1 [上页状态(http://php.net/manual/en/function.crypt。 PHP)(作为代码中的注释)'//让盐自动生成。如果您要从同一页面使用(添加)'$ user_input =“mypassword”;'然后将其修改为'$ user_input =“mypassword2”;'您会看到它实际上将按预期工作。 –

+0

[重新排列的答案](http://stackoverflow.com/a/20625155/1415724)很有意义,并且“正确的金钱”。你的第一个8个字符不应该是一样的。 –

回答

3

你应该看看this answer to a similar questioncrypt()函数要求您有正确格式的盐。虽然temperpedic是有效的盐(排序)它不是一个真正的格式化盐。

如果你看看at the PHP documentation for the crypt() function有几个例子使用crypt()与不同的散列类型。看看这些例子。

请记住,对于现代Web应用程序的crypt,您应该至少使用SHA-256。

<?php 
$pass1 = "thetimeshallwhintercows"; 
$salt = "temperpedic"; 

echo 'SHA-256:  ' . crypt($pass1, '$5$rounds=5000$' . $salt . '$') . "\n"; 
echo 'SHA-256:  ' . crypt($pass1, '$5$rounds=5000$' . $salt . 'extra$') . "\n"; 
echo 'SHA-256:  ' . crypt($pass1, '$5$rounds=5000$' . $salt . 'evenextra$') . "\n"; 

?> 

[email protected] /tmp $ php lol.php 
SHA-256:  $5$rounds=5000$temperpedic$4g0qFd4Oqr/O.8aZMPiyrO9x5VUaQt14eXPOMr5asK2 
SHA-256:  $5$rounds=5000$temperpedicextra$3BF4dmqrCBuY2UtQpuhxXm4t4KGp1M9OoJPrskM490/ 
SHA-256:  $5$rounds=5000$temperpedicevene$jBsGNFGSAbuL8hdcXsZjHRrH6u4qnXb1bAJ.TOR32A2 
0

我跑你的代码,我得到了: “它的工作原理”

It works! 
teTHe69uKVFMw 
teTHe69uKVFMw 

都看到了OK,是你的示例代码的第9行的一部分。

我认为,如果你只是得到“它的作品”,这是因为你访问http://yourhost/,如果你想运行你的特定脚本,你需要明确指定在网址http://yourhost/yourscript.php

1

为了解释这一点,看看这个文档

的标准的基于DES-隐窝()返回盐作为输出的前两个字符。它也只使用str的前八个字符,所以以相同的八个字符开头的较长的字符串将生成相同的结果(当使用相同的盐时)。

当没有指定正确的盐(在你的情况下)它将使用基于DES的crypt函数。从你的例子

$pass1 = "thetimeshallwhintercows"; 
$salt = "temperpedic"; 

crypt($pass1, $salt); // returns teTHe69uKVFMw 

你有没有注意到,输出的字符的第一个2是相同的前2个字符盐即te

一个重要部分是“它也只使用前八个字符的输入“。这就是为什么你得到相同的输出,即使$pass1$pass2是不一样的。如果你想要一个不同的结果前8个字符不应该是相同的

$pass1 = 'thetimeshallwhintercowz'; 
$pass2 = 'thetimeshallwhintercows'; 

// crypt only uses first 8 chars so 'thetimes' so it basically do this 
crypt('thetimes', 'temperpedic'); 

// That explains why you get the same result 
+0

你有一个点。对我来说肯定值得一个'+ 1' - 我测试了你的理论,而且你很震惊。 –

+0

@ Fred-ii-是的,谢谢你。 – Rezigned

+1

不客气。 –