从mysqli数据库[hash_hmac]比较/检查密码是否正确

时间:2017-01-02 16:40:52

标签: php mysqli

我正在使用:

$password = hash_hmac('sha512', 'salt' . $password, $_SERVER['site_key']); 

在注册时将密码存储并加密到数据库中。

登录:我需要比较密码,我该怎么做?

这是我的完整代码:

<?php

    session_start();

    $mysqli = mysqli_connect("localhost", "", "", "");

    $error = ""; //Variable for storing our errors.

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

    if(empty($_POST["emailadd"]) || empty($_POST["password"])){
    $error = "Both fields are required.";
    }
    else {
    // Define $emailadd and $password
    $emailadd=$_POST['emailadd'];
    $password=$_POST['password'];

    // To protect from MySQL injection
    $emailadd = stripslashes($emailadd);
    $password = stripslashes($password);
    $emailadd = mysqli_real_escape_string($mysqli, $emailadd);
    $password = mysqli_real_escape_string($mysqli, $password);
    $password = hash_hmac('sha512', 'salt' . $password, $_SERVER['site_key']);

    //Check username and password from database

    $sql="SELECT * FROM member WHERE emailadd='$emailadd'";
    $result=mysqli_query($mysqli,$sql);
    $row=mysqli_fetch_array($result,MYSQLI_ASSOC);

    //If username and password exist in our database then create a session.
    //Otherwise echo error.

    if(mysqli_num_rows($result) == 1 and $password == hash_hmac('sha512', 'salt' . $_REQUEST['password'], $_SERVER['site_key'] )){
    $_SESSION['emailadd'] = $login_user; // Initializing Session
    header("location: pages/dashboard.html"); // Redirecting To Other Page
    }else{
    $error = "Incorrect email address or password.";
    }

    }
    } 

?>

我似乎无法做到正确,有人可以建议我,谢谢

1 个答案:

答案 0 :(得分:0)

只需在用户输入密码时对用户输入的密码进行哈希处理,然后在注册时对其进行哈希处理,然后从数据库中获取加密密码并进行比较

$hashPass=hash_hmac('sha512', 'salt' . $password, $_SERVER['site_key']);
$query='SELECT password FROM yourtablename WHERE user=$user';
$getPass1=mysqli_query($link, $query);
$getPass2=mysqli_fetch_row($getPass1);
$getPass=$getPass2[0];
if($hashPass==$getPass){
    // yay password is right
};