Comparison between stored hashed password and hashed input password - php

I am currently doing log in system for my website,
I have 2 files which are
sign_up.php
function createSalt(){
$key = md5(uniqid(rand(), TRUE));
return substr($key, 0, 22);
}
$salt = createSalt();
$hash = hash("sha256", $password);
$password = hash("sha256", $salt.$hash);
$userLevel = '1';
$sql = "INSERT INTO users (username, email, password, salt, dob, userLevel)
VALUES (?,?,?,?,?,?)";
if ($stmt = mysqli_prepare($conn, $sql)) {
mysqli_stmt_bind_param($stmt, "sssssi", $username, $email, $password,
$salt, $birthdate, $userLevel);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
and sign_in.php
if (isset($_POST['username']))
$username = sanitize($_POST['username']);
if (isset($_POST['password']))
$password = sanitize($_POST['password']);
$sql = "SELECT *
FROM users
WHERE username = '$username'";
$queryresult = mysqli_query($conn, $sql);
if (!$queryresult)
echo "Unable to query table". mysqli_error();
else{
//get the data from database
while($row = mysqli_fetch_array($queryresult)) {
$salt = $row['salt']; //salt retrieved from the database
$dbpassword = $row['password']; //password retrieved from the database
$finalhash = hash("sha256", $password);
$finalhash1 = hash("sha256", $salt.$finalhash);
//check the password inputed by user to the database
if ($finalhash1 == $dbpassword){
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
echo "Hi $row[1], you are now logged in as $row[3]";
die ("<p><a href=administrator_page.php>Click here to continue</a></p>");
}
else
echo "<h2> Invalid username/password combination \n</h2>";
I don't know why my hashed password from user input always have extra value
I tried to echo it and this is the result:
f0b2dbf93305ce2eef8f5a1f45ab8b1046a7b9ba8ee2f305c3 --> stored password in mySQL
f0b2dbf93305ce2eef8f5a1f45ab8b1046a7b9ba8ee2f305c3f2fce10d5f199f --> inputed password from user
Can someone help me please? Really appreciate it thanks!

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);

Cant verify users hashed password - mysql & php

im trying to verify the users hashed password with their input but i cant get it working, so far it idenfities if theres a user with that username but it just wont verify the password. here is my code
<?php
$serverName = "localhost"; //Variables to access the user database
$username = "root";
$password = "";
$database = "snake_database";
$errors = []; //Array of all the errors to display to the user
$conn = mysqli_connect($serverName, $username, $password, $database); //Connect to the database
if(!$conn){ //If the database failed to connect
die("Database failed to connect: " .mysqli_connect_error()); //Display an error message
}
$username = $_POST['username']; //set the username/ password varaibles
$password = $_POST['password'];
$hashPass = password_hash($password, PASSWORD_DEFAULT); //Encrypt the password
$sql = "SELECT * FROM users WHERE username = ?"; //Select all usernames and passwords
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$count = mysqli_num_rows($result); //Count how many results there are
if ($count == 1)
{
$sql = "SELECT password FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
if(password_verify($password, $result )){
$count = 2;
}
}
if($count == 2) //If there is 1 account that matches
{
$stmt->close(); //Close the statment and connection
$conn->close();
session_start();
$_SESSION["LoggedUser"] = $username; //Log the user in
$_SESSION["lastPage"] = "login.php";
header("location: profile.php"); //Direct the user to their profile
}else //if there is no accounts that match
{
array_push($errors, "Username or password is incorrect");
session_start();
$_SESSION["loginErrors"] = $errors;
$_SESSION["lastPage"] = "login.php"; //Make this page the last page
header("location: index.php"); //Go to the homepage
}
?>
any help is appriciated, thanks
You are doing a lot of things you dont need to do.
A SELECT * will return all the columns so you dont need to do another SELECT for just the password.
Also you should not password_hash() the password again, when checking a password against the one already stored on the database. Use password_verify() and that will do all the checking. So you pass it the hashed_password from the database and the plain text password the user just entered on the screen, it will return true or false telling you if the password entered matched the hashed one on the database
<?php
// always do this early in the code
session_start();
$serverName = "localhost";
$username = "root";
$password = "";
$database = "snake_database";
$errors = []; //Array of all the errors to display to the user
$conn = mysqli_connect($serverName, $username, $password, $database);
if(!$conn){
die("Database failed to connect: " .mysqli_connect_error());
}
// dont hash password again
//$hashPass = password_hash($password, PASSWORD_DEFAULT);
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_POST['username']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
if(password_verify($_POST['password'], $row['password'] )){
// ----------------^^^^^^^^^^^^^^^^^^--^^^^^^^^^^^^^^^^
// Plain text pwd hashed pwd from db
$_SESSION["LoggedUser"] = $_POST['username'];
$_SESSION["lastPage"] = "login.php";
header("location: profile.php");
// put exit after a redirect as header() does not stop execution
exit;
}
} else {
$errors[] = "Username or password is incorrect";
$_SESSION["loginErrors"] = $errors;
$_SESSION["lastPage"] = "login.php";
header("location: index.php");
exit;
}
?>

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
}

How to hash a password with random salt?

Here is my code for hashing a password with random salt. But unfortunately, it doesn't want to work, it gives an incorrect password.
Part one of the script where the user encodes his credentials.
<?php
echo "enter the username \n";
$username = trim(fgets(STDIN));
echo "enter the password\n";
$password = trim(fgets(STDIN));
//connecting to database
$con=mysqli_connect("localhost","sqldata","sqldata","accounts");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$salt = time();
$hashedPassword = sha1($password . $salt);
echo "$hashedPassword";
mysqli_query($con,"INSERT INTO login (username, salt, password)
VALUES ('$username', '$hashedPassword','$salt')");
mysqli_close($con)
?>
The second part of the script where the user enters his credentials.
<?php
echo "enter the username \n";
$username = trim(fgets(STDIN));
echo "enter the password\n";
$password = trim(fgets(STDIN));
//connecting to database
$db = mysql_connect("localhost","sqldata","sqldata") or die(mysql_error());
//selecting our database
$db_select = mysql_select_db("accounts", $db) or die(mysql_error());
$result= mysql_query("select * from login where username = '$username' ");
if ( !$result ) exit("$userName wasn't found in the database!");
$row = mysql_fetch_array($result);
$storedPassword = $row['password'];
$salt = $row['salt'];
$hashedPassword = sha1($password . $salt);
if ( $storedPassword != $hashedPassword ) {
exit( 'incorrect password!' );
} else {
echo "ok";
}
?>
You're storing the salt in the password column, and vice-versa.
mysqli_query($con,"INSERT INTO login (username, salt, password)
VALUES ('$username', '$hashedPassword','$salt')");
Changes this to:
mysqli_query($con,"INSERT INTO login (username, password, salt)
VALUES ('$username', '$hashedPassword','$salt')");

Cant Login in my Hashed password but there's one user that can login

Halo there,
I have a problem of logging in my registered user, I've hashed the passwords and when I log in my form refuse, So I don't really know whats the problem because the user I registered Directly with sql command can actually login below is my login script...
<?php
include 'db_connect.php';
include 'functions.php';
sec_session_start(); // Our custom secure way of starting a php session.
if(isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p']; // The hashed password.
if(login($email, $password, $mysqli) == true) {
// Login success
echo 'Success: You have been logged in!';
echo 'Close window';
} else {
// Login failed
header('Location: ./login.php?error=1');
}
} else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
?>
And Below is my login function on the Function.php file
function login($email, $password, $mysqli) {
if ($stmt = $mysqli->prepare(
"SELECT id, username, password, salt
FROM members
WHERE email = ?
LIMIT 1"
)) {
$stmt->bind_param('s', $email);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password, $salt);
$stmt->fetch();
$password = hash('sha512', $password.$salt); // hash the password with the unique salt.
if($stmt->num_rows == 1) {
if(checkbrute($user_id, $mysqli) == true) {
return false;
} else {
if($db_password == $password) {
$ip_address = $_SERVER['REMOTE_ADDR'];
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$user_id = preg_replace("/[^0-9]+/", "", $user_id); // XSS protection as we might print this value
$_SESSION['user_id'] = $user_id;
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password.$ip_address.$user_browser);
// Login successful.
return true;
} else {
$now = time();
$mysqli->query(
"INSERT INTO login_attempts (user_id, time)
VALUES ('$user_id', '$now')"
);
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
below is how I Register the user to the DB
<?php
include 'db_connect.php';
include 'functions.php';
$password = $_POST['p'];
$username = $_POST['username'];
$email = $_POST['email'];
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
$password = hash('sha512', $password.$random_salt);
if ($insert_stmt = $mysqli->prepare(
"INSERT INTO members (username,email,password,salt)
VALUES (?, ?, ?, ?)"
)) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
// Execute the prepared query.
$insert_stmt->execute();
echo 'Member Succesfully added to the Website list';
} else {
echo 'Error couldnt add the user, Try again';
}
?>
I am guessing you have either randomely changed the password somehow, when you sign up---sha512( $password) and login should be the same in order to match it when quering the data---The $Salt is a bit confusing to?
Login
$_POST['password'] = stripslashes($_POST['password']);
$password = mysql_real_escape_string(sha512($_POST['password']));
Signup
$_POST['password'] = stripslashes($_POST['password']);
$password = mysql_real_escape_string(sha512($_POST['password']));

Categories