2009-10-19 45 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