How to hash a password with random salt? - php

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

Related

Cannot Compare with md5 password from database

signup.php
$password_unencrypted = $_POST['passwd'];
$password=md5($password_unencrypted);
$query = "INSERT INTO Customers (firstname, lastname, username, password, " . "gender,mobile,email) " . "VALUES ('$first_name', '$last_name', '$user_name', '$password', " . " '$gender','$mobile','$email')";
Login.php
$username=$_POST['username'];
$password=md5($_POST['password']);
$sql = ("select * from Customers where username='".$username."' and password='".$password."'") or die('Error connecting to MySQL server.');
$query = mysqli_query($con,$sql);
$result=mysqli_fetch_row($query);
if($result)
{
$_SESSION['username']=$username;
header('location:home.html');
}
else
{
echo md5($_POST['password']);
echo 'Your entered username or password is incorrect';
}
In above signup and login codes I'm applying md5 for password storing
I checked in Database the md5 password is storing correctly but is not retreiving properly(i think)
trying to login into page it is failing
FYI : echo md5($_POST['password']); in Login.php is showing same password stored in database
here is it how to fix your login.php code
you were totally checking wrong you need to check first if the query succeeded running then check if returned rows are more than 0 that means the username is correct and we proceed to password checking if everything is fine we start the session assuming you have session_start() on top of your page if not add it before $_SESSION['username'] = $username;
check the manual for password_hash() and password_verify()
on register.php modify saving the password into the database
$password = md5($_POST['password']); to $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
<?php
if isset($_POST['submit']) {
$username= mysqli_real_escape_string($con, trim($_POST['username']));
$password = trim($_POST['password']); // no need to sanitize the password
$sql = "select * from Customers where username = '" .$username."' "; // you don't need or Die() it's just a string
if ($result = mysqli_query($con,$sql)) //check if the Query succeeded running
{
$count = mysqli_num_rows($result);
if($count > 0 )
{ // if username exists we proceed to checking password
$fetch = mysqli_fetch_assoc($result);
$hashedpassword = $fetch["password"];
if ( password_verify($password, $hashedpassword) )
{ //checking password
$_SESSION['username']=$username;
header('location:home.html');
exit;
}else {
echo "incorrect username or password"; // you don't want to tell him that the username is fine but the password is not correct
}
} else {
echo "incorrect username or password";
}
} else {
echo 'Query failed to run';
}
}
?>

User Authentication Password Hashes [duplicate]

This question already has answers here:
Where to put password_verify in login script?
(2 answers)
Closed 7 years ago.
Okay so i'm trying to make a basic user authentication system. Well I already made it. But what im trying to do now is check the users password against a hash. I'm using $hash = password_hash($password, PASSWORD_DEFAULT); but for the login page I want to check the users password with the hashed password in the database so they can login. How can I do this?
Register.php:
<?php
include('config.php');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function mres($input){
if (get_magic_quotes_gpc()){
$input = stripslashes($input);
}
return mysqli_real_escape_string($conn, $_POST['$input']);
}
$email=mysqli_real_escape_string($conn, $_POST['email']);
$username=mysqli_real_escape_string($conn, $_POST['username']);
$password=mysqli_real_escape_string($conn, $_POST['password']);
$hash = password_hash($password, PASSWORD_DEFAULT);
$query = $conn->query("select * from users where username='$username'");
$rows = mysqli_num_rows($query);
if ($rows == 1) {
echo "User already exist redirecting in 5 seconds!";
} else {
$sql = "INSERT INTO users (username, password, email)
VALUES ('$username', '$hash', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
header("Location: ../index.php");
?>
Login.php:
<?php
session_start();
include('config.php');
$error='';
if (isset($_POST['submit'])) {
if (empty($_POST['userid']) || empty($_POST['passid'])) {
$error = "Username or Password is invalid";
}
else
{
$user=mysqli_real_escape_string($conn, $_POST['userid']);
$pass=mysqli_real_escape_string($conn, $_POST['passid']);
$hash = password_hash($pass, PASSWORD_DEFAULT);
$passv = password_verify($pass, $hash);
$query = $conn->query("select * from users where password='$passv' AND username='$user'");
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username;
$_SESSION['username']=$user;
$_SESSION['checklogin']== true;
header("location: ../profile.php");
} else {
$error = "Username or Password is invalid";
}
mysqli_close($conn);
}
}
?>
(Yes i know i added that function there that im not using in register. Its for future use im saving it for now. I have plans for it.)
Select the password from database using the username. Get the hash password from the database and use password_verify(inputPassword,hashPassword) with an if statement.

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!

PHP login system with encryption (doesn't log in)

I'm struggling with an aspect of something I am trying to do. I am trying to create a basic password management system but I cannot login with an encrypted password. The password does get encrypted on the DB after using the account management page, but when I log out and try to log back in it no longer works.
Here is my code for the login page and change password page: I am aware that SQL injection is a problem but I haven't got round to sorting that part out yet.
LOGIN2.PHP
<link rel="stylesheet" type="text/css" href="default.css" media="screen"/>
<?php
session_start();
$dbname = "obsidian";
if(isset($_POST['sub'])){
//encryption for salt---------------------------------
function makeSalt($salt_length)
{ // only these characters are allowed in salt strings
$saltset = './0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// note that this method only allows up to 6 duplicate chars
$saltchar = "$saltset$saltset$saltset$saltset$saltset$saltset";
// shuffles string randomly & grabs 1st n for our salt
$salt = substr(str_shuffle($saltchar), 0, $salt_length);
return $salt;
}
//Login Script
$username = $_POST['username'] ;
$password = $_POST['password'] ;
//ENCRYPTS THE USER ENTERED PASSWORD
$salt = '$5$rounds=1000$' . makeSalt(16) . '$';
$hashed_password = crypt($password, $salt);
//CONNECT TO DB
$mysqli = new mysqli('localhost','admin1', 'password1','obsidian' ) or die('Failed to connect to DB' . $mysqli->error );
$sSQL = "select * from users where password='$hashed_password' AND username='$username'";
$result = mysqli_query( $mysqli, $sSQL);
if (!$sSQL) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$row = mysqli_fetch_array($result);
if(!$row){
echo "<div>";
echo "No existing user or wrong password.";
echo "</div>";
session_destroy();
header("Location: index.php");
}
else {
$_SESSION['userid'] =$username;
header("Location: index.php");
}
}
?>
And this is the PHP script for the changing of passwords.
<?php
session_start();
$dbname = "obsidian";
if(isset($_POST['change'])){
//CREATE SALT-------------------------------------------------------------------------
function makeSalt($salt_length)
{ // only these characters are allowed in salt strings
$saltset = './0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// note that this method only allows up to 6 duplicate chars
$saltchar = "$saltset$saltset$saltset$saltset$saltset$saltset";
// shuffles string randomly & grabs 1st n for our salt
$salt = substr(str_shuffle($saltchar), 0, $salt_length);
return $salt;
}
//Entered credentials from form---------------------------------------------------------
$oldPass = $_POST['oldPass'];
$newPass = $_POST['newPass'];
$newPassAgain = $_POST['newPassAgain'];
//Connect to DB-------------------------------------------------------------------------------
$mysqli = new mysqli('localhost','admin1', 'password1','obsidian' ) or die('Failed to connect to DB' . $mysqli->error );
//CHECK IF OLD PASS AND SESSION ID EQUAL-----------------------------------------------------
$sSQL = ("select * from users WHERE password='$oldPass' AND username= '" . $_SESSION["userid"] . "'");
$result = mysqli_query( $mysqli, $sSQL);
if (!$sSQL)
{
printf("Error: %s\n", mysqli_error($con));
exit();
}
$row = mysqli_fetch_array($result);
//IF THERE ARE NO ROWS, DO NOT CHANGE PASSWORD-------------------------------------------
if(!$row)
{
echo "<div>";
echo "No existing user or wrong password.";
header("Location: account.php");
echo "</div>";
session_destroy();
}
//IF THERE ARE ROWS ENCRYPT AND CHANGE PASSWORD----------------------------------------
else {
$salt = '$5$rounds=1000$' . makeSalt(16) . '$';
$hashed_password = crypt($password, $salt);
if ($newPass == $newPassAgain){
$update = ("UPDATE users SET password = '$hashed_password' where username= '" . $_SESSION["userid"] . "'") or die (mysql_error());
if ($mysqli->query($update) === TRUE) {
echo "Record updated successfully";
header("Location: success.php");
}
else {
echo "Error updating record: " . $mysqli->error;
}
}
}
}
A point in the right direction would be appreciated.
Thanks
You are hashing a password with a random salt each time.
Example code:
echo makeSalt(16) . "\n";
echo makeSalt(16) . "\n";
echo makeSalt(16) . "\n";
Outputs:
oAv0cGIzTECgF1gI
ypZegnQoS.d/inqA
6PPXZ/.YfupGuxPg
In order for the hash to be the same, the salt has to be the same. Though having the same salt for every user is not as secure as having a different hash for every user.
You could for example consider making the salt based on the username, or store the salt and the hash and then select the salt and encrypted password from the database for the user who is attempting to login.
Then the hash should match if you hash the supplied password with the same salt.
Furthermore, consider using sha_512 instead of sha__256. ($5$ -> $6$).
Also consider using mysqli or PDO as you will have more secure queries (Less chance on mysql injections).
(Pseudoish code)
(Insert code)
$salt = '$6$rounds=1000$' . makeSalt(16) . '$';
$hashed_password = crypt($password,$salt);
insert into table (password_salt,password_hash...) values($salt,$hashed_password,.....);
(Verify code)
select password_salt, password_hash.... from table where user = username
if(hash_equals(crypt($password,$password_salt),$password_hash)){
//OK
}else{
//Wrong password!
}
Your encryption system is safe and secure just as this
$user_input = "someone";
$pass_input = "something";
$auth_credentials = hash("sha512", md5(sha1(md5($user_input . $pass_input))));
echo $auth_credentials;
test and feedback.

Password verifying against database using bcrypt

Im trying to verify a password against the one in the database but it doesn't work.
Please see my code and let me know what's wrong.
Code for storing username and password to the database.
<?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 = substr(sha1(mt_rand()),0,22);
$hashedPassword= crypt($password , '$2y$10$' . $salt);
echo $hashedPassword;
mysqli_query($con,"INSERT INTO login (username, password)
VALUES ('$username', '$hashedPassword')");
mysqli_close($con)
?>
Code for verifying password is as follows
<?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 = substr(sha1(mt_rand()),0,22);
$hashedPassword= crypt($password , '$2y$10$' . $salt);
if (crypt($hashedPassword) == $storedPassword)
{
echo "ok";
}
else
{
echo "error";
}
?>
When you save you password to the database you are using:
$hashedPassword= crypt($password , '$2y$10$' . $salt);
but when you retrieve the password and check it I see a couple of things wrong:
$storedPassword = $row['password'];
$salt = substr(sha1(mt_rand()),0,22);
$hashedPassword= crypt($password , '$2y$10$' . $salt);
if (crypt($hashedPassword) == $storedPassword){/*...*/}
1, shouldn't:
$hashedPassword= crypt($password, '$2y$10$' . $salt);
be
$hashedPassword= crypt($storedPassword, '$2y$10$' . $salt);
2, It appears that you are using crypt twice:
$hashedPassword= crypt($password , '$2y$10$' . $salt);
if (crypt($hashedPassword) == $storedPassword)
so shouldn't is just be:
$hashedPassword= crypt($storedPassword, '$2y$10$' . $salt);
if ($hashedPassword == $storedPassword){/*...*/}
This is simpler than you are thinking. The crypt format is somewhat clever: it includes the salt as the start of the crypted password, in the form (method)(salt)(hash).
When using crypt(), it only looks at (method)(salt) and uses them to return (method)(salt)(hash), so to verify a password, all you need to do is pass the crypted password as the salt and see if the result matches. That is to say,
crypt($testPassword, $hashedPassword) === $hashedPassword

Categories