PHP hashing prob - php

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
}

Related

How to verify password whith 2 different forms?

I have 2 forms : one for Registration and one for Login ([not on the same page, one is a modal][1])
(That's why I did 2 issets at the beginning)
The Registration one is working.
However the Login doesn't work because a User can log in with any password.
I want to verify username/email and of course password. How can I do it ?
Thank you!
Here is my code :
// REGISTRATION
if (isset($_POST['reg_user']) || isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['name']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = "SELECT * FROM utilisateur WHERE pseudoUtil='$username' OR mailUtil='$email'";
$results = mysqli_query($db, $query);
if(mysqli_num_rows($results) == 1){
$_SESSION['message'] = "User already exists !";
}
else{
mysqli_query($db, "INSERT INTO utilisateur (pseudoUtil, mailUtil, pwdUtil) VALUES ('$username', '$email', '$hashed_password')");
$_SESSION['message'] = "Registration complete :)";
}
// LOGIN
if (isset($_POST['login_user'])) {
$query2 = "SELECT $hashed_password FROM utilisateur WHERE pseudoUtil='$username' OR mailUtil='$email'";
$results2 = mysqli_query($db, $query2);
if(mysqli_num_rows($results2) == 1){
$_SESSION['username'] = $username;
header('location: index.php');
}
else{
}
}
}
else{
}
[1]: https://i.stack.imgur.com/fCdAV.png
registration needs to create the password hash and save it to the database, log in needs to pull the hash from the database and compare to the password
both of these tasks should be complete isolated from each other
this means your code should look more like this
note this is an example only not tested as working
POST /register body: username=someone#some.where&password=123456789
function Register(){
$stmt = $mysqli->prepare("SELECT count * as count FROM users WHERE email=?");
$stmt->bind_param("s", $_POST["username"]);
$stmt->execute();
$result = $stmt->get_result();
if($result->fetch_array(MYSQLI_ASSOC)["count"]>0)
{
return "User already exists"
}
else
{
$hash = password_hash($_POST["password"],PASSWORD_DEFAULT);
$stmt = $mysqli->prepare("INSERT INTO users (username, hash) values (?,?)");
$stmt->bind_param("ss", $_POST["username"], $hash);
$stmt->execute();
$result = $stmt->get_result();
//either return success or set up as a successful login and perform login action
}
}
POST /login body: username=someone#some.where&password=123456789
function Login(){
$stmt = $mysqli->prepare("SELECT hash FROM users WHERE email=?");
$stmt->bind_param("s", $_POST["username"]);
$stmt->execute();
$result = $stmt->get_result();
if(password_verify($_POST["password"], $result->fetch_array(MYSQLI_ASSOC)["hash"]))
{
//do successful login
}
else
{
//log in failed
}
}

Login page keeps showing error PHP and MySQL

I am having issues getting some simple (or it seems simple) coding to cooperate. I've tried stripping it completely and typing everything out. Here is the code:
<?php
session_start();
if(isset($_POST['login'])) {
$username = trim($_POST['username']);
$password = md5(trim($_POST['password']));
include('includes/admin.php');
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) == 0) {
echo '<p>Incorrect login.<br>Return to Login Page</p>';
} else {
$_SESSION['user'] = $username;
echo '<p>Login successful.<br>Go to Admin Page</p>';
}
}
?>
The goal is to have it redirect to the login page if unsuccessful and to redirect to another admin page if successful. I keep getting the "Incorrect Login" error, even when I type in the correct username and password.
Side Note: I know to redirect, I need to use header('Location: link.php'), it is not included for testing purposes.
If you didn't save your password as MD5 hash in your database you will never match it, cause in the line above you hash the password via MD5 before using in the query.
MD5 isn't secure! Use the PHP internal functions (password_hash(), password_verify()) to create and check passwords!
Use prepared statements!
Example code:
<?php
// Save a new user password in DB
$username = 'Max User';
$password = 'My_Secr3t_Pa5sw0rd';
$passwordHash = password_hash($password, PASSWORD_BCRYPT);
$stmt = $mysqli->prepare("INSERT INTO `users` (`username`, `password`) VALUES(?, ?)");
$stmt->bind_param("ss", $username, $passwordHash);
$stmt->execute();
// Check user password
$stmt = $mysqli->prepare("SELECT `password` FROM `users` WHERE `username`=?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if (password_verify($password, $row['password']) {
echo "Password correct";
} else {
echo "Password incorrect!";
}
?>

Comparison between stored hashed password and hashed input password

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!

password_verify hash not matching password

I have generated a password hash using the code below:
$hash = password_hash("test", PASSWORD_BCRYPT);
I then store it in the database using a 255 char.
Then I try to do the comparator to test the login and it fails. It only lets me login using a hash I have just generated a few lines before, not one stored in the database.
<?php
//Database connection
require 'database.php';
//Handle logins
if ($_POST['login'])
{
//Receive the login attempt
$login_email = $_POST['login_email'];
$login_password = $_POST['login_password'];
//Get the password hash
if ($statement = $mysqli->prepare("SELECT password FROM accounts WHERE email = ? LIMIT 1"))
{
$statement->bind_param("s", $login_email);
$statement->execute();
$statement->store_result();
//Does the account exist?
if ($statement->num_rows > 0)
{
$statement->bind_result($hash);
$statement->fetch();
//echo $login_password;
echo $hash."<br>";
//$hash = password_hash("test", PASSWORD_BCRYPT);
//echo $hash."<br>";
//Check the password hash
if (password_verify($login_password, $hash))
{
echo '<br>Password is valid!';
//Begin session
session_start();
$_SESSION["favcolor"] = "yellow";
}
else
{
echo '<br>Invalid password.';
}
}
else
{
//Account doesn't exist warning
}
$statement->free_result();
$statement->close();
}
}
//Handle new registrations
if ($_POST['register'])
{
//Receive the register attempt
$register_email = $_POST['register_email'];
$register_password_one = $_POST['register_password_one'];
$register_password_two = $_POST['register_password_two'];
//Check if email is already taken
if ($statement = $mysqli->prepare("SELECT email FROM accounts WHERE email = ? LIMIT 1"))
{
$statement->bind_param("s", $register_email);
$statement->execute();
$statement->store_result();
//Does the account exist?
if ($statement->num_rows > 0)
{
//Account already exists warning
}
else
{
//Create the account
if ($statement = $mysqli->prepare("INSERT INTO accounts (email, password) VALUES (?,?)"))
{
//Create bycrypt hash of password
$hash = password_hash($register_password_one, PASSWORD_BCRYPT);
//Insert new account
$statement->bind_param("ss", $register_email, $hash);
$statement->execute();
$account_id = $statement->insert_id;
$statement->close();
//Begin session
session_start();
$_SESSION["favcolor"] = "yellow";
}
}
$statement->free_result();
$statement->close();
}
}
//Handle logout
if ($_POST['logout'])
{
session_unset();
session_destroy();
}
?>
password hash in database: $2y$10$xDnZIjzw8h.9utp3qyRlxezPd8jmK9k6Z5JuoVtooOpkPCBd.n6W6
password hash that is just generated (works): $2y$10$tolDQdeTQrTio8IJ0Wi9AuHN5Km28pSB5kUh5qfkdkOsDXP295H1K
I am not an expert with hashing. Just trying to follow the latest recommendations. Could someone tell me why the hash is different to the one in the database?
the hash generated is different every time
pass plain text to the password_verify() function... see below
$originalPassword = password_hash("THE_PASSWORD", PASSWORD_DEFAULT);
// This will produce something like (taken form above)
$2y$10$tolDQdeTQrTio8IJ0Wi9AuHN5Km28pSB5kUh5qfkdkOsDXP295H1K
// When verifying this
if(password_verify("THE_PASSWORD", $passwordFromDatabase['password'])){
echo "Success";
}else{
echo "Fail";
}

hash generated on register not same as on login

I generate a hashed password on user registration but when trying to log in the hashed password generate is different so i cant log in
reg: (ill be adding checks and verification once i get hashed password working)
session_start();
require_once('connect.php');
$login = $_POST['login'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
if($login == '') {
echo "Email missing";
}
if($password == '') {
echo "Password missing";
}
if($cpassword == '') {
echo "Password missing";
}
if( strcmp($password, $cpassword) != 0 ) {
echo "Passwords do not match";
}
$stmt = $db->prepare("INSERT INTO members (Email, Password) VALUES (:login, :password)");
$stmt->bindValue( ":login", $login );
$stmt->bindValue( ":password", hash("sha512", $password, $salt));
$stmt->execute();
if ($stmt)
{
header("location: ?p=register-success");
exit();
}
login:
session_start();
include_once ('connect.php');
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$stmt = $db->prepare("SELECT * FROM members WHERE Email = :Email AND Password = :Password");
$stmt->bindParam(":Email", $Email);
$stmt->bindParam(":Password", hash("sha512", $Password, $salt));
$stmt->execute();
$member = $stmt->fetch(PDO::FETCH_ASSOC);
if ($member)
{
$_SESSION['SESS_MEMBER_ID'] = $member['Member_ID'];
$_SESSION['SESS_POST_AS'] = $member['Post_As'];
$_SESSION['SESS_AUTH'] = $member['auth'];
session_write_close();
header('location: index.php');
} else {
header("location: ?p=login-failed");
}
my salt: (a fixed set of characters for testing only)
$salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";
i checked if they were the same by echoing the hashed password before they were submitted on a related note, once the hashed password is stored in my table it isnt the same as the one submitted on register the one in the table has ?? in place of some special characters
The third parameter to hash determines whether the output from the hash is raw, i.e. not encoded as hexadecimal. Your salt is truthy, so the output is raw, and your database is trying to encode it as a string.
You probably meant to use hash_hmac. But switch to Bcrypt anyways; a fixed salt isn’t that useful.
This is the prototype for the hash function
string hash ( string $algo , string $data [, bool $raw_output = false ] )
So you need to do something like this:
$saltedPwd = $password . $salt;
$hashedSaltedPwd = hash("sha512", $saltedPwd);
$stmt = $db->prepare("INSERT INTO members (Email, Password) VALUES (:login, :password)");
$stmt->bindValue( ":login", $login );
$stmt->bindValue( ":password", $hashedSaltedPwd);
$stmt->execute();
Then make similiar changes to yuor login page.

Categories