比较发布的密码与MySQL存储的加密密码

时间:2014-11-26 09:29:41

标签: php mysql mysqli

我的SQL表:

|-ID-|-Username-|-EmailAddress-|-ePassword-|-Permissions-|
----------------------------------------------------------
|  1 |    Admin |              |           |             |
|  2 |       Foo|<emailaddress>|<cpassword>|  <default 1>|
|    |          |              |           |             |
|    |          |              |           |             |

以下代码从表单中获取_POST数据,然后引用数据库以检查用户名是否正确,一旦用户名正确,我希望能够将$password与{{ePassword进行比较1}}来自我的数据库,

ePassword使用crypt加密。来自php.net关于地穴的一个例子说我必须这样做:

if (hash_equals($hashed_password, crypt($user_input, $hashed_password)) {
    echo "Password verified!";
}

比较密码,所以我的是:

if (hash_equals($hashed_password, crypt($password, $hashed_password)) { //changed $user_input to password
    echo "Password verified!";
}

但是我如何从数据库中获取ePassword并进行比较呢?

//User data
$username = strtolower($_POST['username']);
$password = $_POST['password'];

//login check
if($_SESSION['loggedIn'] != "") {
    echo 'You already are using an Account!';
} else if($_SESSION['loggedIn'] == "") {

    //connect to database
    $con =  mysqli_connect($db_host, $db_user, $db_pass, $db_name);

    //check for connection errors
    if (!$con) {
        die('Could not connect: ' . mysql_error());
    };

    //checks for username
    $stmt = $con->prepare("SELECT * FROM Users WHERE Username=?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();

    $userCheck = $stmt->num_rows;
    if($userCheck > 0) {
                                //Password check goes here
    } else {

    };
    $con->close();
};

TL; DR:我想将$password与我的数据库中的ePassword与crypt进行比较,我该怎么做?

2 个答案:

答案 0 :(得分:0)

    // username and password sent from Form
    $username=$_POST['username'];
    $password=$_POST['password'];

    $password=crypt($password,saltUsedWhileRegisteringUser); // Encrypted Password
    //Assuming ePassword is the crypted password inserted into DB while User Registeration
    $sql="SELECT id FROM admin WHERE username='$username' and ePassword ='$password'";

    $result=mysql_query($sql);

    $count=mysql_num_rows($result);//If count > 1 then valid user else not a valid one.

答案 1 :(得分:0)

if($userCheck > 0) {
    //Password check goes here
    $stmt->bind_result($id, $username,$emailAddress,$ePassword,$permissions);
    $password = crypt($password,'the same salt used to create ePassword. without it the string will be always random'); 
    if (hash_equals($password,$ePassword) {
        echo 'user logged in';
    else
        echo 'invalid password';
    }
}