2 回答

TA貢獻2039條經(jīng)驗 獲得超8個贊
SHA- *算法不能安全存儲密碼,而是使用函數(shù)password_hash()生成安全的BCrypt哈希。它將使鹽分別存儲變得無關緊要

TA貢獻1936條經(jīng)驗 獲得超7個贊
開發(fā)人員通常很難驗證登錄密碼,因為他們不確定如何處理存儲的密碼哈希。他們知道密碼應該使用適當?shù)暮瘮?shù)(如password_hash()進行哈希處理,并將它們存儲在一個varchar(255)字段中:
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_DEFAULT);
在登錄表單中,我們無法直接使用SQL驗證密碼,也無法搜索密碼,因為存儲的哈希值已被加密。相反,我們......
必須從數(shù)據(jù)庫中讀取密碼哈希,按用戶ID搜索
然后可以使用password_verify()函數(shù)檢查找到的哈希值的登錄密碼。
您可以在下面找到一些示例代碼,展示如何使用mysqli連接進行密碼驗證。代碼沒有錯誤檢查以使其可讀:
/**
* mysqli example for a login with a stored password-hash
*/
$mysqli = new mysqli($dbHost, $dbUser, $dbPassword, $dbName);
$mysqli->set_charset('utf8');
// Find the stored password hash in the db, searching by username
$sql = 'SELECT password FROM users WHERE username = ?';
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $_POST['username']); // it is safe to pass the user input unescaped
$stmt->execute();
// If this user exists, fetch the password-hash and check it
$isPasswordCorrect = false;
$stmt->bind_result($hashFromDb);
if ($stmt->fetch() === true)
{
// Check whether the entered password matches the stored hash.
// The salt and the cost factor will be extracted from $hashFromDb.
$isPasswordCorrect = password_verify($_POST['password'], $hashFromDb);
}
請注意,該示例使用預準備語句來避免SQL注入,在這種情況下不需要轉義。從pdo連接讀取的等效示例可能如下所示:
/**
* pdo example for a login with a stored password-hash
*/
$dsn = "mysql:host=$dbHost;dbname=$dbName;charset=utf8";
$pdo = new PDO($dsn, $dbUser, $dbPassword);
// Find the stored password hash in the db, searching by username
$sql = 'SELECT password FROM users WHERE username = ?';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(1, $_POST['username'], PDO::PARAM_STR); // it is safe to pass the user input unescaped
$stmt->execute();
// If this user exists, fetch the password hash and check it
$isPasswordCorrect = false;
if (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false)
{
$hashFromDb = $row['password'];
// Check whether the entered password matches the stored hash.
// The salt and the cost factor will be extracted from $hashFromDb.
$isPasswordCorrect = password_verify($_POST['password'], $hashFromDb);
}
添加回答
舉報