哈希密码PHP mySQLI

时间:2016-03-03 20:59:22

标签: php mysql

所以即时尝试使用户输入的密码在存储在我的数据库中时会被加密。有了BCRYPT我能够做到这一点,但是现在加密存储在数据库中,用户无法使用他们选择的密码登录。 有没有人有任何建议我将如何继续这个?

感谢任何帮助!

提前致谢!

Register.php page below

<?php
require 'C:\wamp\www/projekt/connections.php';

if(isset($_POST['submit'])) {


session_start();
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$uname = $_POST['username'];
$pwd = $_POST['password'];

$hashedpassword = password_hash($pwd, PASSWORD_DEFAULT);



$sql = $con->query("INSERT INTO users (FirstName, LastName, UserName,   Password)VALUES('{$fname}', '{$lname}', '{$uname}', '{$hashedpassword}')");

if (password_verify($pwd, $hashedpassword)) {


 header('Location: login.php'); 
 }



 }

 ?>

----------------------------------------------------------

login.php page below

<?php

$con = mysqli_connect("localhost","root","","userreg");

if(isset($_POST['login'])){

$uname = mysqli_real_escape_string($con,$_POST['Username']);

$pwd = mysqli_real_escape_string($con,$_POST['Password']);

$sel_user = "select * from users where UserName='$uname' AND Password='$pwd'";

$run_user = mysqli_query($con, $sel_user);

$check_user = mysqli_num_rows($run_user);

if($check_user>0){

$_SESSION['UserName']=$uname;

echo "<script>window.open('startpage.php','_self')</script>";

}

else {

echo "<script>alert('Username or password is not correct, try again!')</script>";



}

}

?>

1 个答案:

答案 0 :(得分:3)

您可以使用php的password_hash和password_verify。它既有哈希值,也有盐密码。

//Store $hashedPassword in the database under the password column.
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);

//Or you could use PASSWORD_DEFAULT over PASSWORD_BCRYPT which will default to php's current default method. 
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);


//Query the database and pull out the hashed password.
//Pass the user entered password and the retrieved/stored hash into the password_verify method. 
//If it is a match, it will return true.
if (password_verify($password, $hashedPassword)) {
   // Correct password
}

编辑:以下是流程应如何散列/存储/验证密码。

(创建新用户 - 密码)

  1. 取用户输入(务必清理所有用户输入/使用准备好的语句!看看PDO / MySQLI)

  2. 哈希密码。 $hashedPassword = password_hash($password, PASSWORD_DEFAULT);参数$password是用户输入。

  3. 将新变量/散列密码$hashedPassword存储到您的数据库中。

  4. 此时,用户已创建,其密码/其他信息已存储到数据库中。

    (记录用户)

    1. 取用户输入(务必清理所有用户输入/使用准备好的语句!看看PDO / MySQLI)

    2. 查询您的数据库并检索用户密码(从数据库中选择用户名/ id等于他们输入的密码)。

    3. 将步骤1中的用户输入和步骤2中检索到的密码传递给方法:password_verify($password, $hashedPassword) - $password是用户输入,$hashedPassword是密码我们从数据库中提取。如果密码匹配,此方法将返回true,否则返回false。

    4. -

      if (password_verify($password, $hashedPassword)) {
      
       // Correct password
       //Set the session variables/whatever else you would like to do now that we have verified that the user has the correct password.
      
      } else {
      
       //Redirect the user/inform them that they have the incorrect username/password combination.
      
      }