从md5更改为sha256

时间:2009-10-19 16:54:52

标签: php authentication hash

我正在尝试构建一个安全的用户身份验证系统。

代码来自 http://net.tutsplus.com/tutorials/php/simple-techniques-to-lock-down-your-website/

但我试图从md5改为sha-256,但它不会登录。

我刚从

改变了
$auth_pass = md5( $row['salt'] . $password . $stat_salt );

$auth_pass = hash('sha256', $row['salt'] . $password . $stat_salt );

它确实正确地插入到db,但登录部分由于某种原因不能正常工作。适用于md5但不适用于sha256。你是否必须以不同的方式使用sha256?

注册:

// generate a unique salt
$salt = uniqid(mt_rand());

// combine them all together and hash them
$hash = hash('sha256', $salt . $password . $stat_salt );

// insert the values into the database
$register_query = mysql_query("INSERT INTO users (username, password, salt) VALUES ('".$username."', '".$hash."', '".$salt."')") or die("MySQL Error: ".mysql_error());

登录

// grab the row associated with the username from the form
$grab_row = mysql_query("SELECT * FROM users WHERE username = '".$username."'") or die ("MySQL Error: ".mysql_error());

// if only one row was retrieved
if (mysql_num_rows($grab_row) == 1) {

// create an array from the row fields
$row = mysql_fetch_array($grab_row);

// re-hash the combined variables
$auth_pass = hash('sha256', $row['salt'] . $password . $stat_salt );

// check the database again for the row associated with the username and the rehashed password
$checklogin = mysql_query("SELECT * FROM users WHERE username = '".$username."' AND password = '".$auth_pass."'") or die("MySQL Error: ".mysql_error());

// if only one row is retrieved output success or failure to the user
if (mysql_num_rows($checklogin) == 1) {
echo "<h1>Yippie, we are authenticated!</h1>";
} else {
echo '<h1>Oh no, we are not authenticated!</h1>';
}
} else {
echo '<h1>Oh no, we are not in the database!</h1>';
}
}

1 个答案:

答案 0 :(得分:5)

  

它确实正确地插入db,但是[...]

你是如何测试的? md5返回32位字符串,hash('sha256', ...)返回64位字符串。您的password字段是否足够长以容纳它?如果不是,则插入$hash将被剪切到字段的长度,并且选择的比较将失败。