2015-04-22 124 views
0

有人可以告訴我如何當某人登錄時驗證散列密碼嗎?如何驗證用戶登錄時的散列密碼

這裏是我的註冊代碼:

$db_password = password_hash($password, PASSWORD_DEFAULT); 

// Enter info into the Database. 
$info2 = htmlspecialchars($info); 
$sql = mysql_query("INSERT INTO users 
        (first_name, last_name, email_address, username, password, signup_date) 
        VALUES('$first_name', '$last_name', 
          '$email_address', '$username', 
          '$db_password', now())") 
       or die (mysql_error()); 

這是在登錄時運行我的檢查用戶代碼。 。

$hash = password_hash($password, PASSWORD_DEFAULT); 

// check if the user info validates the db 
$sql = mysql_query("SELECT * 
        FROM users 
        WHERE username='$username' 
         AND password='$hash' 
         AND activated='1'"); 
$login_check = mysql_num_rows($sql); 

我找不出來。

+0

忘記登錄時我正在會見憑據無效消息 – user3205214

+2

當您檢查口令來添加的,你看從現有的散列數據庫並使用[password_verify()](http://www.php.net/manual/en/function.password-verify.php)檢查用戶輸入的密碼 –

+0

請[停止使用'mysql_ *'函數](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。他們不再被維護,並[正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。瞭解[準備的陳述](http://en.wikipedia.org/wiki/Prepared_statement),並使用[PDO](http://jayblanchard.net/demystifying_php_pdo.html)。另外,你在查詢中使用變量的方式會讓我相信你可能是[SQL注入。]的受害者(http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection -in-php) –

回答

2

你的驗證是錯誤的...你再次哈希密碼,這將導致一個全新的鹽...因此一個完全不同的哈希值。當密碼被散列(正確)時,他們使用足夠長的鹽(隨機字符串)來防止彩虹攻擊。 password_hash正在幕後爲你做這一切。

但是,這意味着您必須確保使用相同的鹽,以便通過將密碼與散列一起存儲來驗證密碼。在你使用的代碼的情況下,它正在爲你做這部分,鹽是password_hash結果的前綴。

當用戶登錄時,你需要做的:

if(password_verify($loginPasswordText, $hashStoredInDb)) { 
    //SUCCESS 
} 
0

無需密碼在登錄時再次散列,使用簡單password_verify()功能在登錄時間確認您存儲的密碼&給定的密碼。查看更多有關密碼散列API這裏http://php.net/manual/en/ref.password.php

現在試試這個樣子,

<?php 
    // this is the example hashed password that you have to select from Database. 
    $hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq'; 

    if (password_verify('password_given_at_login', $hash)) { 
     echo 'Password is valid!'; 
    } else { 
     echo 'Invalid password.'; 
    } 
    ?>