2012-07-05 109 views
1

好的,所以下面的所有代码都不是我自己的。我一直在关注互联网上的教程,但是当我尝试并运行它时,没有看到任何密码匹配。我相信,在密码中添加密码可能会有错误,因为数据库中的密码远不及login.php脚本中描述的64个字符。我不知道。代码如下:哈希/盐渍时密码不匹配

register.php

// Create a 256 bit (64 characters) long random salt 
// Let's add 'something random' and the username 
// to the salt as well for added security 
$salt = hash('sha256', uniqid(mt_rand(), true) . 'something random' . strtolower($username)); 

// Prefix the password with the salt 
$hash = $salt . $password; 

// Hash the salted password a bunch of times 
for ($i = 0; $i < 100000; $i ++) 
{ 
    $hash = hash('sha256', $hash); 
} 

// Prefix the hash with the salt so we can find it back later 
$hash = $salt . $hash; 

// carry on with registration code... 

的login.php

$email = $_POST['email']; 
$password = $_POST['password']; 

$con = mysql_connect("localhost", "redacted", "redacted", "redacted"); 

$sql = ' 
    SELECT 
     `password` 
    FROM `users` 
     WHERE `email` = "' . mysql_real_escape_string($email) . '" 
    LIMIT 1 
    ;'; 

$r = mysql_fetch_assoc(mysql_query($sql)); 

// The first 64 characters of the hash is the salt 
$salt = substr($r['password'], 0, 64); 

$hash = $salt . $password; 

// Hash the password as we did before 
for ($i = 0; $i < 100000; $i ++) 
{ 
    $hash = hash('sha256', $hash); 
} 

$hash = $salt . $hash; 

if ($hash == $r['password']) 
{ 
    session_start(); 
    header('Location: /quiz/index.php'); 
} 

if($hash != $r['password']){ 
    session_start(); 
    header('Location: /?error=4'); 
} 

// end login script 
+0

哪个教程? PHP在网上有很多低劣的教程。这似乎是其中之一。 – alex

+3

常见的错误是数据库字段长度不足以存储所有字符。 – Konerak

+0

啊......这就是为什么。我的密码字段只有30个字符。欢呼@Konerak :-) –

回答

2

一个常见的错误是当数据库字段不够长时存储所有字符。那么密码将永远不会与用户输入的内容相同。

对于这种功能,总是写单元测试,检查函数(仍然)是否按预期工作。有一天,有人会修改数据库,更改散列算法,修改盐......没有人能够登录。

-1

它看起来像您要添加的盐2次:

$hash = $salt . $password; 

// Hash the password as we did before 
for ($i = 0; $i < 100000; $i ++) 
{ 
    $hash = hash('sha256', $hash); 
} 

//skip the below one 
$hash = $salt . $hash; 

更新:

事实上,在这种情况下需要添加盐2次。

尽管盐应该保存在一个单独的数据库列中,所以代码将更加简化 - 通过避免所有字符串连接来存储/检索salt。

除此之外,您的数据库结构将更接近第三范式通过将每条信息存储在一个单独的插槽中。

+3

跳过整个“无数次哈希”。只要使用可引入工作因素的东西,通常建议使用bcrypt。 – alex

+2

你需要存储盐与散列,以便你可以知道它是什么后。 –

+0

事实证明,我的密码数据库字段太短。但感谢所有的建议。 –