Blowfish password_verify doesn't do the job - php

I'm hashing my passwords with blowfish using Anthony Ferrara's password compactibility library. When I hash 'em they're good, BUT when I try to verify the passwords, doing this:
public function Login($username, $postpassword) {
$stmt = $this->mysqli->prepare("SELECT username, password FROM users WHERE username=? AND password=?");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) {
while($stmt->fetch()) {
if (password_verify($postpassword, $password)) {
$SESSID = $this->newSession($username);
$_SESSION['admin_user'] = $username;
$_SESSION['last_login'] = time();
header("Location: home.php?SESSID=$SESSID");
exit();
}
}
}
else {
header("Location: index.php?e=false");
exit();
}
$stmt->close();
$stmt->free_result();
}
It tells me that me details are wrong... And YES, i did define the $username and $password:
if(isset($_REQUEST['login'])) {
$username = $_POST['username'];
$postpassword = $_POST['password'];
$users->Login($username, $postpassword);
}
Does anybody see the mistake I made?

You are selecting the user from the database where the username matches the entered username and the password hash matches the entered plaintext password. Of course this will never match anything. You will have to select the username and password from the database only based on the username, then verify the password using password_verify.

Related

Unable to extract password hash from database with prepared statements

EDIT: To clarify, I am unable to extract the hashed password from my database using prepared statements.
I'm trying to create a login system that uses prepared statements, password_hash and password_verify.
I have created the registering form that creates the user, with the hashed password using password_hash($_POST['password'], PASSWORD_DEFAULT);
This works properly.
However, I am now stuck on creating the login form.
I am trying to get the password hash that gets stored when a user registers but I cannot get it to work with prepared statements.
This is what I currently have.
<?php
require('db.php');
if(isset($_POST['submit'])) {
$stmt = $connect->prepare('SELECT user_name, user_password FROM `users` WHERE user_name = ?');
if($stmt) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
}
}
?>
How do I use the data that I got from the select query? And how do I use it to verify the password?
I tried:
$stmt->store_result();
$stmt->bind_result($loginUsername, $hash);
That only stored the username, but not the password hash and I have no clue why.
Verifying the password would use this?
password_verify($password, $hash);
UPDATE
<?php
require('db.php');
if(isset($_POST['submit'])) {
$stmt = $connect->prepare('SELECT user_name, user_password FROM `users` WHERE user_name = ?');
if($stmt) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
// Get query results
$result = $stmt->get_result();
// Fetch the query results in a row
while($row = $result->fetch_assoc()) {
$hash = $row['user_password'];
$username = $row['user_name'];
}
// Verify user's password $password being input and $hash being the stored hash
if(password_verify($password, $hash)) {
// Password is correct
} else {
// Password is incorrect
}
}
}
?>
Read this PHP MANUAL.Try this:
<?php
require('db.php');
if(isset($_POST['submit'])) {
$stmt = $connect->prepare('SELECT user_name, user_password FROM `users` WHERE user_name = ?');
if($stmt) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
// Get query results
$stmt->bind_result($user_name,$hash);
$stmt->store_result();
// Fetch the query results in a row
$stmt->fetch();
// Verify user's password $password being input and $hash being the stored hash
if(password_verify($password, $hash)) {
// Password is correct
} else {
// Password is incorrect
}
}
}
?>
This is how I created my login system:
$stmt = mysqli_prepare($link,"SELECT user_email,user_password,user_firstname,user_lastname,user_role,username FROM users WHERE user_email=?");
mysqli_stmt_bind_param($stmt,"s",$email);
mysqli_stmt_execute($stmt);
confirmQuery($stmt);
mysqli_stmt_bind_result($stmt,$user_email,$user_password,$user_firstname,$user_lastname,$user_role,$username);
mysqli_stmt_store_result($stmt);
mysqli_stmt_fetch($stmt);
if(mysqli_stmt_num_rows($stmt) == 0)
relocate("../index.php?auth_error=l1");
else{
if(password_verify($password,$user_password)){
$_SESSION['userid'] = $user_email;
$_SESSION['username'] = $username;
$_SESSION['firstname'] = $user_firstname;
$_SESSION['lastname'] = $user_lastname;
$_SESSION['role'] = $user_role;
if(isset($_POST['stay-logged-in']))
setcookie("userid", $email, time() + (86400 * 30), "/");
relocate("../index.php?auth_success=1");
}else
relocate("../index.php?auth_error=l2");
}
mysqli_stmt_close($stmt);

Hash verification error in php

I would like to verify my stored hashed passwords with the inputs that the users insert.
What theory says...
After read about the mechanism of password_hash and password_verify, I realized that, theoretically, the string that is inserted will be compared with a hash, which, at least in my case, is stored in the site db.
What is happening to me...
I register my users with password_hash and then to verify the login I use password_verify. If I am good and the code is right, this function should verify the input of the user (even if it's plain text(?) ) with the stored hash.
Let's see the code:
Registration code:
$passwordHash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
Note: There is more code but I guess that this is the most important part so I decided to paste only this part.
Login code:
<?php
//controller!
require "../model/backend.php";
$username = $_POST['user'];
$password = $_POST['password'];
$dbcom = new dbInteraction;
$dbcom->admlog($username, $password);
$dbcom->conclose();
?>
Verification code:
$this->username = $username;
$this->password = $password;
//$this->pdo = $pdo;
//$adm = 1;
$myquery = 'SELECT username, password, isadmin FROM users WHERE username = :username';// AND password = :password';
$stmt = $this->pdo->prepare($myquery);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if($user === false){
die('1Incorrect username / password combination!');
} else{
//Compare the passwords.
$dbpass = $user['password'];
echo $dbpass;
echo '<br>bd<br>input<br>';
echo $password;
$validPassword = password_verify($dbpass, $password);
echo '<br>debug <br>';
echo 'pre pass:<br>';
echo $validPassword;
if($validPassword){
//Provide the user with a login session.
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
//header('Location: home.php');
exit;
}else{
die('<br>no pass--Incorrect username / password combination!');
}
}
Do I have some theoretical base problem in my code or it's just bad coded? I'm still trying to realize.
Thank you very much.
The problem was in the order of password_verify params.
It should be like $validPassword = password_verify($password, $dbpass);
or in generic words:
$validPassword = password_verify('String to verify', 'Saved password');
Special thanks to #JonStirling

PHP hashing prob

I am doing a Registration / Login and I can't get hashed passwords to match.
if(isset($_POST["pass"])) {
$pass = $_POST["pass"];
$options = array('cost' => 11);
$pass = password_hash("$pass", PASSWORD_BCRYPT, $options)."\n";
}
$sql2 = $db->prepare('INSERT INTO Registrace (Email, Password, Nick) VALUES (:email, :password, :nick)');
$sql2->execute(array(':email' => $email,':password' => $pass, ':nick' => $nick));
Hashed password has been entered in Database.
Now, how do I make the password in login match the one in databse?
if(isset($_POST["pass"])) {
? ? ? ? ?
}
$sql = $db->prepare("SELECT Nick,Password FROM registrace WHERE Nick=:nick AND Password=:password");
$sql->bindParam(':nick', $_POST['lognick']);
$sql->bindParam(':password', $pass);
$sql->execute();
if($row = $sql->fetch()){
$_SESSION['lognick'] = $row['lognick'];
$_SESSION['lognick'] = $_POST["lognick"];
$_SESSION['time'] = time();
header("Location: Logged.php");
}
else {
$_SESSION['error'] .= "Pass and Nick don't match. ";
header("Location: Login.php");
}
Any idea what to do ?
What you'll need to do is find the username in the database and retrieve the hash, then pass it to password_verify
$sql = $db->prepare("SELECT Nick,Password FROM registrace WHERE Nick=:nick");
// PDO binds and execute here
if($row = $sql->fetch()) {
if(!password_verify($_POST['password'], $row['Password']) { //login fail
Look up the password hash and then check the entered password as follows:
if (password_verify($_POST['pass'], $row['Password'])) {
// Logged in
} else {
// Wrong password
}

PHP password_hash and password_verify Not Working with MySQL

I am using password_hash to store passwords in a MySQL database field of type VARCHAR(255). When I try to login the user and verify credentials, the password_verify function always returns false.
Here is the code excerpt that stores the password in the MySQL database:
$password_hash = password_hash($password, PASSWORD_DEFAULT);
// Generate API Key
$api_key = $this->generateApiKey();
// Insert Query
$stmt = $this->conn->prepare("INSERT INTO user(email, password, name, api_key, status) values(?, ?, ?, ?, 1)");
$stmt->bind_param("ssss", $email, $password_hash, $name, $api_key);
$result = $stmt->execute();
$stmt->close();
And the piece of code that checks the password:
// Query user by email
$stmt = $this->conn->prepare("SELECT password FROM user WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($password_hash);
$stmt->store_result();
if ($stmt->num_rows > 0) {
// Found user with that email address
// Now verify the password
$stmt->fetch();
$stmt->close();
if (password_verify($password, $password_hash)) {
// User password is correct
return TRUE;
Then I wrote this test code and grabbed the data straight from the MySQL field and it still fails. When I create the password_hash in the same file ($hash2 in the file below) - then the password verifies correctly.
$password = 'pass1234567890';
$hash = '$2y$10$JLP/pPei6RYRdUmoH8H5RO7iJyImOtrBLsrRRfq3XpeqNE3lQ/l7O';
$hash2 = password_hash($password, PASSWORD_DEFAULT);
echo $hash . " - " . strlen($hash);
echo "<br />";
echo $hash2 . " - " . strlen($hash2);
echo "<br />";
if (password_verify($password, $hash)) {
echo "Password Valid!";
} else {
echo "Password invalid!";
}
echo "<br /><br />";
if (password_verify($password, $hash2)) {
echo "Password 2 Valid!";
} else {
echo "Password 2 invalid!";
}
This proves that something is wrong with your hash
<?php
// See the password_hash() example to see where this came from.
$password = 'pass1234567890';
$hash = '$2y$10$JLP/pPei6RYRdUmoH8H5RO7iJyImOtrBLsrRRfq3XpeqNE3lQ/l7O';
$hash2 = '$2y$10$gMJKYZUc1FKSZBnsONxLOebOHj.uuEWSiCP0jo4Zv0iAHBz6iz.NG';
if (password_verify('pass1234567890', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
echo "<br>";
if (password_verify('pass1234567890', $hash2)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
Screenshot
In my case the probme was that I stored the database connection query in another file which included the same variable that I used for fetching current password, so what happened was that first I assigned a variable "password" to current password and then included my connection query file which had the same variable "password" therefore what happened was that, "password" variable of signup form was reassigned by "password" variable of connection query, and that's why it actually hashed another password. So by changing the variable name this problem was solved.
Here is my code for reference,
signup.php
$email = $_POST["email"];
$password = $_POST["password"];
include 'partials/php/_dbconnect.php';
$passwordHash = password_hash($passwd, PASSWORD_DEFAULT);
_dbconnect.php
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "demo";
$connectionquery = mysqli_connect($server, $username, $password, $database);
?>
which I changed to;
$email = $_POST["email"];
$passwd = $_POST["password"];
include 'partials/php/_dbconnect.php';
$passwordHash = password_hash($passwd, PASSWORD_DEFAULT);
password_verify($password,trim($password_hash)))
While I am unsure if it happened when the hash was stored or during retrieval, the password_hash had a space at the end. Trimming the hash before feeding it to password_verify fixed the issue for me.
Just make a variable for if(password_verify($pass_input, $pass_db))
where $pass_input is the value given from the textified form and $pass_db is the value stored in mysql (hashed)
Like this:
$verif_pass = (password_verify($pass_input, $pass_db));
if($verif_pass){echo "TRUE"} else {echo "FALSE";}
and just modify TRUE/FALSE as you want.

Why does my script skips trhough the If statements with mysql query

I'm trying to make a login script for a project that I have. I came accross an open source and i typed some and copy/paste some. I went through the whole thing. I found that the login Function on the if statement where it says mysql->prepare is just skipping. I do not know if it is something with the database or an error on the script.
The place where I got the script was this
http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
my test page is ertechs.t15.org is the login.php for logging in.
username is test_user#example.com and the password is 6ZaxN2Vzm9NUJT2y.
Thanks in advance.
and this is where i'm having the problem. this function
function login($email, $password, $mysqli) {
echo "Function login";
// Using prepared statements means that SQL injection is not possible.
$prep_smt = "SELECT id, username, password, salt FROM members WHERE email = ? LIMIT 1";
$smt = $mysqli->prepare($prep_smt);
if ($stmt)
{
echo "Tst passed";
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $username, $db_password, $salt);
$stmt->fetch();
// hash the password with the unique salt.
$password = hash('sha512', $password . $salt);
echo "password= =".$password;
if ($stmt->num_rows == 1) {
echo "row";
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
echo "brute true";
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
echo "pass match";
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
echo "pass correct";
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512',
$password . $user_browser);
// Login successful.
return true;
} else {
echo "Password Failed";
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
} else {
echo "user doesnt exist";
// No user exists.
return false;
}
echo "whatever";
}
echo "end Function Login";
}
$smt = $mysqli->prepare($prep_smt);
if ($stmt)
Notice the missing t in $stmt?

Categories