2009-10-19 41 views
0

我正在尝试构建一个安全的用户身份验证系统。从md5更改为sha256

的代码是从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>'; 
} 
} 
+0

什么是'$ stat_salt'? – Gumbo 2009-10-19 16:58:43

+0

哦,你不需要数据库查询。只需将'hash'调用的返回值与'$ row ['password']'中的值进行比较即可。 – Gumbo 2009-10-19 17:00:28

+0

stat_salt是我为所有用户提供的盐 – 2009-10-19 17:14:58

回答

5

它插入到正确的DB,但[...]

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

+0

即使不是,修剪后的SHA结果是不是应该一样? – fbrereto 2009-10-19 17:12:06

+0

削减沙沙的结果与它有什么关系? OP的比较'varchar's – SilentGhost 2009-10-19 17:14:42

+1

那是我的密码字段的问题是32 varchar 非常感谢你! – 2009-10-19 17:16:41