存储和检索 SHA-256 散列和加盐密码的正确方法

2022-01-22 00:00:00 hash passwords security salt php

这是我第一次尝试安全地存储密码,我想确保一切都正确完成.有人建议我将 SHA-256 散列与 salt 一起使用.

This is my first attempt in securely storing passwords and I would like to make sure that everything is done correctly. I was advised to use SHA-256 hashing alongside salt.

假设用户提交了完整的密码表单,我们通过

Assuming user submitted their password thorough form, we get the password via

$password = $_POST["password"];

什么是加盐 $password 并对其使用 SHA-256 散列的正确方法,因此它可以存储在数据库中的密码字段密码 CHAR(64)"中?

What is correct way to salt $password and use SHA-256 hashing on it, so it can than be stored in a password field "password CHAR(64)" in a database?

完成并存储后,我将如何将数据库中存储的值与登录表单中输入的用户进行比较?假设 $loginPassword = $_POST["loginPassword"]; 是用户输入的内容.

Once done and stored how would I than compare value stored in a database to one user entered in a login form? Lets assume $loginPassword = $_POST["loginPassword"]; is what user entered.

推荐答案

你可以使用 crypt() 函数为你加盐.

Instead of using SHA family methods, you can use the crypt() function to salt it for you.

这是一个使用 PDO 的示例脚本(保存和登录).

Here is an example script (save and login) using PDO.

在数据库中保存密码

<?php
// Set the password
$password = 'mypassword';

// Get the hash, letting the salt be automatically generated
$hash = crypt($password);

echo $hash; // for testing purposes only

$mysql_username = 'username'; // for DB
$mysql_password = 'password'; // for DB

$dbh = new PDO('mysql:host=localhost;dbname=database_name', $mysql_username, $mysql_password);

$stmt = $dbh->prepare("INSERT INTO table_name (name,pass) VALUES (:name,:pass)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':pass', $pass);

// insert rows
// $name = $_POST['name'];
// $name = $_POST['pass'];

$name = "username";
$pass = $hash;
$stmt->execute();

登录脚本

<?php
$mysql_username = 'username'; // for DB
$mysql_password = 'password'; // for DB

$dbh = new PDO('mysql:host=localhost;dbname=database_name', $mysql_username, $mysql_password);

/*
$username = $_POST['username'];
$password = $_POST['password'];
*/

$username = "username";
$password = "mypassword";

$sql = "SELECT * FROM table_name WHERE name=:username";
$statement = $dbh->prepare($sql);
$statement->bindValue(':username',$username,PDO::PARAM_STR);

if($statement->execute())
{
    if($statement->rowCount() == 1)
    {
        $row = $statement->fetch(PDO::FETCH_ASSOC);

 if (crypt($password, $row['pass']) === $row['pass'])

        {
            $username = $row['name'];
            $email = $row['email'];

echo "Stage 1";

echo "<hr noshade size="1">";

echo "Hello " .$username;

            exit;
        }
        else
        {
            // include "error_login.php";

echo "Stage 2 - ERROR";

        }
    }
    else
    {
       // include "error_login.php";

echo "Stage 3 error";
    }
}

相关文章