On my registration page I have used an SHA1 has and a salt to store my passwords in the database. I think I have done this correctly as when I check the database it is has with the salt included. This is how I have done it.
$newPassword = $_POST['Password'] ;
if (!empty($newPassword)) {
//Escape bad characters
//$newuser = mysql_real_escape_string($newuser);
//remove leading and trailing whitespace
$newPassword = trim($newPassword);
$newPassword = sha1($newPassword);
$salt = '-45dfeHK/__yu349#-/klF21-1_\/4JkUP/4';
}
else die ("ERROR: Enter a Password");
and input is
$query = "INSERT INTO members (memberFirstname, memberSecondname, memberEmailaddress, memberPassword, memberAddress, memberPostcode) VALUES ('$newFirstName', '$newSecondName', '$newEmailAddress', '$newPassword$salt', '$newAddress', '$newPostcode')";
My problem lays when I try to login. Im unsure on how remove the salt and unhash the password (if that is what needs to be done). I can enter the email address and paste the hash and salt into the password field and can successfully login.
This is my script to log in.
<?php
include 'db.inc';
session_start();
$UserEmail =$_POST["EmailAddress"];
$UserPassword =$_POST["Password"];
$query = "SELECT * FROM members WHERE memberEmailaddress = '$UserEmail'
AND memberPassword = '$UserPassword' ";
$connection = mysql_connect($hostname, $username, $password) or die ("Unable to connect!");
mysql_select_db($databaseName) or die ("Unable to select database!");
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
$_SESSION["authenticatedUser"] = $UserEmail;
// Relocate to the logged-in page
header("Location: Index.php");
}
else
{
$_SESSION["message"] = "Could not connect log in as $UserEmail " ;
header("Location: Login.php");
}
mysql_free_result($result);
mysql_close($connection);
?>
There are several problems with your approach. First you don't use the salt at all, it will be stored but not used. Second a salt should be unique for each password, in your case a static salt is used, this is actually a pepper not a salt. Further you use a fast hash algorithm, but this can be brute-forced ways too fast, instead you should switch to a hash algorithm with a cost factor like BCrypt or PBKDF2.
PHP already has a good function to hash passwords (maybe you need the compatibility pack):
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
Because this function generates a safe salt on its own and attaches it to the resulting hash-value, you cannot check the password with SQL directly. Instead you do a query to get the stored hash (by username), then you can verify the entered password with the stored one. I wrote a tutorial where i tried to explain the important points more indepth.
Related
I think i have hashed password using function PASSWORD directly from mysql database(am i doing wrong here?). And i am trying to verify that password with this code:
if($submit)
{
$first=$_POST['first'];
$password=$_POST['password'];
$hash="*85955899FF0A8CDC2CC36745267ABA38EAD1D28"; //this is the hashed password i got by using function PASSWORD in database
$password=password_verify($password,$hash);
$db = new mysqli("localhost", "root","","learndb");
$sql = "select * from admin where username = '" . $first . "' and password = '". $password . "'";
$result = $db->query($sql);
$result=mysqli_num_rows($result);
if($result>0)
{
session_start();
$_SESSION['logged_in'] = true;
session_regenerate_id(true);
header("Location:loginhome.php");
}
}
But the password is not matching. What am i missing here?
UPDATE:
After all the suggestions i have used password_hash from php code to store into database.
$db = new mysqli("localhost", "root","","learndb");
$password=password_hash('ChRisJoRdAn123',PASSWORD_DEFAULT);
$sql="INSERT INTO admin (username,password)values('ChrisJordan','$password')";
$db->query($sql);
still the password is not matching.
One cannot search for a salted password hash in a database. To calculate the hash you need the password_hash() function as you already did correctly in your insert statement.
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_DEFAULT);
To check a password, you first need to search by username only (used a prepared query to avoid sql injection):
$sql = 'select * from admin where username = ?';
$db->prepare($sql);
$db->bind_param('s', $first);
When you finally got the stored hash from the database, it can be checked like this:
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
password_verify is a boolean function which return either true or false. In your code, after getting value of password from Post param, you doing this operation
$password=password_verify($password,$hash);
which changes the $password value to true or false and that boolean value stored in $password you are using in mysql select statement
$sql = "select * from admin where username = '" . $first . "' and password = '". $password . "'";
Another thing is it might be possible that the hashed/salted password you are using is not the correct hashed value of the password you are using.
Update: Try this
$cost = [
'cost' => 15,
];
$hash_password = password_hash('ChRisJoRdAn123', PASSWORD_BCRYPT, $cost);
before any db operation, change your password field varchar length to >=64
$sql = "INSERT INTO admin (username,password)values('ChrisJordan','".$hash_password."')";
After insert operation, execute the select statement with the user
$sql = "select * from admin where username = 'ChrisJordan'";
after this fetching hased password and password from the post parameter, you will need to verify both passwords using password_verify
if (password_verify(validate($_POST['password']), $hash_password_from_db)) {
echo "Valid Password";
}else{
echo "Invalid Password";
}
You must use password_hash to encode passwords verified with password_verify.
The MySQL function PASSWORD is something entirely different. It is used for encoding passwords specific to MySQL authentication. (MySQL specifically recommends against using PASSWORD for anything other than MySQL authentication.)
The two use different hashing algorithms, present their output in different formats, and are generally not compatible with each other.
The typical way to use password_hash and password_verify is:
$hash = password_hash($password, PASSWORD_DEFAULT);
//Store $hash in your database as the user's password
//To verify:
//Retrieve $hash from the database, given a username
$valid = password_validate($password, $hash);
The problem in your code is that you're doing this:
$password=password_verify($password,$hash);
$sql = "select * from admin where username = '" . $first . "' and password = '". $password . "'";
password_verify returns a boolean (whether the password and hash matched). Instead, you need to retrieve the hash from the database and match the entered password with that hash.
This is too long for a comment.
Seeing that this question has yet to contain a green tick next to any of the answers, am submitting the following in order to point out probable issues.
I noticed that you are trying to move over from MD5 to password_hash() - password_verify().
Your other question Switching from md5 to password_hash
What you need to know is that MD5 produces a 32 character length string, as opposed to password_hash() being a 60 length.
Use varchar(255).
If you kept your password column's length to 32, then you will need to clear out your existing hashes from that column, then ALTER your column to be 60, or 255 as the manual suggests you do.
You will need to clear out all your existing passwords, ALTER your column, create a new hash, then try your login code again.
I see this in your code:
"*85955899FF0A8CDC2CC36745267ABA38EAD1D28"; //this is the hashed password i got by using function PASSWORD in database
This string *85955899FF0A8CDC2CC36745267ABA38EAD1D28 is 40 long, which is too short and has been cut off.
This tells me that your column's length is 40, instead of 60, or again as the manual suggests, 255.
MD5 reference:
http://php.net/manual/en/function.md5.php
Returns the hash as a 32-character hexadecimal number.
Reference for password_hash():
http://php.net/manual/en/function.password-hash.php
The result will always be a 60 character string, or FALSE on failure.
To ALTER your column, here is a reference link:
http://dev.mysql.com/doc/refman/5.7/en/alter-table.html
Also make sure that your form contains a POST method and that the inputs bear the matching name attributes and that no whitespace gets introduced.
You can use trim() to get rid of those.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
as well as or die(mysqli_error($db)) to mysqli_query().
Edit:
What you need to do is fetch an array and get the match on that.
$sql = "select * from admin where username = '".$first."' and password = '".$password."' ";
$result = $db->query($sql);
if ($result->num_rows === 1) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (password_verify($password, $row['password'])) {
//Password matches, so create the session
// $_SESSION['user']['user_id'] = $row['user_id'];
// header("Location:/members");
echo "Match";
}else{
echo "The username or password do not match";
}
}
Another possible solution:
$query = "SELECT * from admin WHERE username='$first'";
$result = $db->query($query);
if($result->num_rows ===1){
$row = $result->fetch_array(MYSQLI_ASSOC);
if (password_verify($password, $row['password'])){
echo "match";
} else {
$error = "email or Password is invalid";
echo $error;
}
}
mysqli_close($db); // Closing Connection
I'm learning PHP and as a project I started building a social network. I did create the signup form and login form and I can add users to my database. I also hash their passwords. This is a simple site and a work in progress so there are a lot of security holes.
My problem is with the login file, I can't seem to match the user with the password he has given me. For verifying the user password I use the password_verify() function but it doesn't seem to be working right.
Here is my code:
Sign up
<?php
//signUp.php
//Here is where I add a user in my database
//I validate the input, confirm that the password is written like it should be
//check if a user with the same username exists in the database
//if all checks out I will add the user in the database
//and redirect the user to his profile
require_once 'login.php';
require_once 'helperFunctions.php';
$conn = new mysqli($servername, $username, $password, $database);
if(!$conn)
die("Connection failed:" . mysqli_connect_error());
$myUsername = $_POST['Name'];
$myPassword = $_POST['Password'];
$myConfirm = $_POST['conPass'];
sanitize($conn, $myUsername);
sanitize($conn, $myPassword);
//check if the two passwords are the same
if($myPassword != $myConfirm){
print "Your passwords don't match";
header("refresh: 5; index.html");
} else {
//check if username already exists in database
$query = "SELECT * FROM members WHERE Username='$myUsername'";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if($count == 0){
//hash password
$hashedPass = password_hash("$myPassword", PASSWORD_DEFAULT);
//username doesn't exist in database
//add user with the hashed password
$query ="INSERT INTO members (Username, Password) VALUES ('{$myUsername}', '{$hashedPass}')";
$result = mysqli_query($conn, $query);
if(!$result)
die("Invalid query: " . mysqli_error());
else{
print "You are now a member or The Social Network";
header("refresh: 5; login_success.php");
}
} else {
print "Username already exists";
header("refresh: 5; index.html");
}
}
?>
Login
<?php
//checkLogin.php
//Here is where I authenticate my users and if successfull I will show them their profile
require_once 'login.php';
require_once 'helperFunctions.php';
$conn = new mysqli($servername, $username, $password, $database);
if(!$conn)
die("Connection failed:" . mysqli_connect_error());
//Values from form
$myUsername = $_POST['Name'];
$myPassword = $_POST['Password'];
//sanitize input
sanitize($conn, $myUsername);
sanitize($conn, $myPassword);
$query = "SELECT * FROM members WHERE Username='$myUsername'";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if($count == 1){
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
print "hashedPass = ${row['Password']}";
print "myPassword: " . $myPassword;
if(password_verify($myPassword, $row['Password'])){
print "Password match";
} else
print "The username or password do not match";
}
?>
Sanitize function
function sanitize($conn, $val){
$val = stripslashes($val);
$val = mysqli_real_escape_string($conn, $val);
}
By running the program print "hashedPass = ${row['Password']}"; prints out the hashed password which is the same with the one I have on my database but for some reason I get redirected to the print "The username or password do not match"; statement after this.
Comment pulled and taken from a deleted answer:
"I remembered that when I first created the database I used CHAR(10) for the passwords while the hashed password needs more characters."
so the almighty answer here is that your password column is 50 characters short.
password_hash() creates a 60 characters string.
the manual states that it is best to use VARCHAR and with a length of 255 in order to accommodate for future changes.
http://php.net/manual/en/function.password-hash.php
the solution to this now, is to start over with a new registration and then login again using what you are presently using.
Example from the manual:
<?php
/**
* We just want to hash our password using the current DEFAULT algorithm.
* This is presently BCRYPT, and will produce a 60 character result.
*
* Beware that DEFAULT may change over time, so you would want to prepare
* By allowing your storage to expand past 60 characters (255 would be good)
*/
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT)."\n";
?>
The above example will output something similar to:
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
Also from the manual:
Caution
Using the PASSWORD_BCRYPT for the algo parameter, will result in the password parameter being truncated to a maximum length of 72 characters.
PASSWORD_DEFAULT - Use the bcrypt algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).
PASSWORD_BCRYPT - Use the CRYPT_BLOWFISH algorithm to create the hash. This will produce a standard crypt() compatible hash using the "$2y$" identifier. The result will always be a 60 character string, or FALSE on failure.
Supported Options:
Another comment/question pulled from the deleted answer:
"Can I alter my password field without having to delete my table and start from the beginning?"
The answer is yes. See this Q&A on Stack:
How can I modify the size of column in a mysql table?
You can also consult:
https://dev.mysql.com/doc/refman/5.0/en/alter-table.html
Sidenote: You will still need re-enter new hashes for the (old) affected column(s).
Plus, as already stated; you are open to SQL injection. Use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
Can someone please tell me how i am suppose to verify a hashed password when someone is logging in?
here is my registration code:
$db_password = password_hash($password, PASSWORD_DEFAULT);
// Enter info into the Database.
$info2 = htmlspecialchars($info);
$sql = mysql_query("INSERT INTO users
(first_name, last_name, email_address, username, password, signup_date)
VALUES('$first_name', '$last_name',
'$email_address', '$username',
'$db_password', now())")
or die (mysql_error());
this is my check user code run at login . .
$hash = password_hash($password, PASSWORD_DEFAULT);
// check if the user info validates the db
$sql = mysql_query("SELECT *
FROM users
WHERE username='$username'
AND password='$hash'
AND activated='1'");
$login_check = mysql_num_rows($sql);
i can not figure it out.
Your verification is wrong...you are hashing the password all over again, which will result in a brand-new salt...thus a completely different hash value. When passwords are hashed (correctly), they use a salt (random string) that is sufficiently long to prevent a rainbow attack. password_hash is doing all of this behind the scenes for you.
However, this means you have to make sure to use the same salt in order to verify the password by storing it along with the hash. In the case of the code you are using, it's doing this part for you and the salt is the prefix of the result of password_hash.
When the user logs in, you need to do:
if( password_verify($loginPasswordText, $hashStoredInDb) ) {
//SUCCESS
}
No need to password hashing again at login time, Use simply password_verify() function to verify your stored password & given password at login moment. See more about Password Hashing API here http://php.net/manual/en/ref.password.php
For now Try like this,
<?php
// this is the example hashed password that you have to select from Database.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify('password_given_at_login', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
My login form isn't recognising existing users. The passwords I have stored in the database are encrypted using PHP's crypt() function. When the user registers their password is also encrypted and inserted into the database.
As you can see in the code below it checks to see if the password entered below matches, but whenever I enter in a password that is stored in the database with the corresponding username it says that the user does not exist.
I'm new to PDO and this is my first time using it, normally if I just use MySQL it works fine, but for some reason this isn't, I have changed the code a bit yet it still does not work. Anyone know why/where/what I'm doing wrong with the code.
include "connect.php";
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username=:username";
$statement = $db->prepare($sql);
$statement->bindValue(':username',$username,PDO::PARAM_STR);
if($statement->execute())
{
if($statement->rowCount() == 1)
{
$row = $statement->fetch(PDO::FETCH_ASSOC);
if(crypt($password, $row['username']) == $row['user_password'])
{
$username = $row['username'];
$email = $row['email'];
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['logged_in'] = 1;
header("Location: index.php");
exit;
}
else
{
include "error_login.php";
}
}
else
{
include "error_login.php";
}
}
if(crypt($password, $row['username']) == $row['user_password'])
Should be
if(crypt($password) == $row['user_password'])
To verify a password with its stored hash-value, you need to know the salt and the algorithm that was used to generate the hash-value before. This salt can be extracted from the stored hash-value, because crypt() stores it as part of the resulting string.
if (crypt($password, $row['user_password']) === $row['user_password'])
PHP 5.5 will have it's own functions password_hash() and password_verify() ready, to simplify generating BCrypt hashes. I strongly recommend to use this excellent api, or it's compatibility pack for earlier PHP versions. The usage is very straightforward:
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
Alright, I'm trying to make a login page. It seems that all of the pages worked pretty good- until I added salts. I don't really understand them, but doing something as basic as I am shouldn't be to hard to figure out. Here's "loginusr.php":
<html>
<body>
<?php
//form action = index.php
session_start();
include("mainmenu.php");
$usrname = mysql_real_escape_string($_POST['usrname']);
$pass = $_POST['password'];
$salt = $pass;
$password = sha1($salt.$pass);
$con = mysql_connect("localhost", "root", "g00dfor#boy");
if(!$con)
{
die("Unable to establish connection with host. We apologize for any inconvienience.");
}
mysql_select_db("users", $con) or die("Can't connect to database.");
$select = "SELECT * FROM data WHERE usrname='$usrname' and password='$password'";
$query = mysql_query($select);
$verify = mysql_num_rows($query);
if($verify==1)
{
$_SESSION["valid_user"] = $usrname;
header("location:index.php");
}
else
{
echo "Wrong username or password. Please check that CAPS LOCK is off.";
echo "<br/>";
echo "Back to login";
}
mysql_close($con);
?>
</body>
</html>
I used the command echo $password; to show me if the password in the database matched with the script. They did. What am I doing wrong?
It seems like you've misunderstood salts, since you're setting $salt to be the password.
A salt should be a completely random string that's stored in a user record along with the password hash. A new unique salt should be generated for every user. So you need to add a new column to your database, called "password_salt" or similar.
Rather than trying to use the password in the SELECT query and see if you get any records, you actually need to just SELECT using the username/user_id in order to get the password hash and salt so that you can then use those to determine if the user entered the correct password.
When you sign up new users you should add the fields with values like this,
<?php
// This is registeruser.php
$salt = substr(sha1(uniqid(rand(), true)), 0, 20);
$pass = $_POST['password'];
$pass_to_store = hash("sha256", $salt.$pass);
// Then issue a DB query to store the $salt and $pass_to_store in the user record.
// Do not store $pass, you don't need it.
// e.g. INSERT INTO users ('username', 'password_salt', 'password_hash') VALUES (:username, :salt, :pass_to_store);
?>
Then to check the password is the same when logging in, you do something like this,
<?php
// This is loginuser.php
$user = // result from SQL query to retrieve user record
// e.g. SELECT password_hash, password_salt FROM users WHERE username='from_user'
$salt_from_db = $user['password_salt'];
$pass_from_db = $user['password_hash'];
if ($pass_from_db == hash("sha256", $salt_from_db.$_POST['password'])
{
// Password matches!
}
?>
Don't forget to sanitize user inputs and anything you're putting into your database. You might want to look into using prepared statements instead of having to remember to use mysql_real_escape_string all the time.
It looks like you're salting with the same password? Normally a salt would be a random key that is specific to your site that you prepend to the password input, which it looks like you're doing fine. Just make sure you're using that same salt for checking that you use when the password is created.
Also, to use sessions properly you need to have session_start before anything is output to the page:
<?php
session_start();
?>
<html>
<body>
...
A salt is a random value to prevent an attacker from just looking up the source of a hash in table generated based on common passwords. (Using the username as salt is obviously not a good idea as it only adds very little entropy).
So you need to store the salt in the database and read it from the database in order to calculate the salted password hash for comparison with the stored value.
You misspelled username a couple of times, is it misspelled in the database, too?