This question already has answers here:
Using PHP 5.5's password_hash and password_verify function
(4 answers)
Closed 7 years ago.
I am using this to hash passwords: https://github.com/ircmaxell/password_compat
$hash = password_hash($pass1, PASSWORD_BCRYPT, array("cost" => 16));
if (password_verify($password, $hash)) {
/* Valid */
} else {
/* Invalid */
}
It works. It hashed passwords. But I dont know how to verify the password in the login page. I have tried with seesions but it doesnt work with sessions too.
you have to put the Hash in Database
Step one : create and store the hash in database
$hash = password_hash($pass1, PASSWORD_BCRYPT, array("cost" => 16));
Step two : login
$hash = // hash of user from database by unique id
$password = // string submit by user from login form
if (password_verify($password, $hash)) {
if (password_needs_rehash($hash, PASSWORD_BCRYPT, array("cost" => 16))) {
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 16));
/* Store new hash in db */
}
} else {
/* Invalid */
}
Hope it will be help you
The way I have done it in the past is in the following steps:
1) User submits their Username/password combination.
2) I see if the Username exists in the database, if it does I pull out that user record from the database, if it doesn't I present a generic error to the user (i.e. wrong username/password combination)
3) I then use the password_verify function with the submitted password against the hashed password connected to the user they are trying to log in as.
4) If its true, they're logged in otherwise I present the same generic error to the user (wrong username/password combination)
Basically you have to hash the password user puts in login page and check if the saved hash in database is equal to hashed password that user sends on login.
Related
This question already has answers here:
How to use PHP's password_hash to hash and verify passwords
(5 answers)
Closed 12 months ago.
I've created a simple login/registration form. The registered information is stored in a .txt file (this is for educational purposes only not real use).
I am hashing the registered input before I put it in the.txt file. When the user logs in I want to use password_verify to check the hash. If the hash is the same as the login input the user is verified and should therefore be logged in.
With the current code, even if the login is the same as what's stored in the.txt file it jumps straight to the }else statement that says username and/or password is incorrect.
EDIT: If I enter username as 123 and password as 123 the textfile shows:
$2y$10$VeZB8AZmL9lAfRQ1qKBxEug8A3RrPxM9JlOAo9prw/UOWU4.XpdqC,$2y$10$kU5AvH4hTgE1cvHmTItIU.pnTsbYvKH9bLl3Bxfy4ig7QZKdVVV46,
I am new to PHP and programming in general and any help is appreciated :)
// GETS FORM INPUT
if(isset($_POST['username']) && $_POST['password']){
$username = $_POST['username'];
$password = $_POST['password'];
$hashName = password_hash($username,PASSWORD_DEFAULT);
$hashPass = password_hash($password, PASSWORD_DEFAULT);
}
// LOGIN
if($_POST['btn'] == 'Login'){
userExist($username, $password, $hashName, $hashPass);
}
// REGISTER
else if(($_POST['btn'] == 'Register')){
$fh = fopen("logininfo.txt", 'a') or die("Unable to open file");
$login = <<<_END
$hashName,$hashPass,
_END;
fwrite($fh, $login) or die("Unable to write to file");
fclose($fh);
}
//VERIFIES USER
function userExist($username, $password, $hashName, $hashPass){
$accounts = file_get_contents('logininfo.txt');
$accArray = explode(',', $accounts);
print_r($accArray);
if((password_verify($hashName, $accArray[0])) && (password_verify($hashPass, $accArray[1]))){
header('Location: index.php');
}else{
echo "username and/or password is incorrect";
}
}
There's too much hashing here.
When registering a user you store the unhashed user name and the password hashed with password_hash()
When logging in you use the unhashed user name to recover the hashed password for that user, then use password_verify() to compare the unhashed password the user has given you with the hashed password you stored.
password_hash() adds a random salt to the password and stores the salt and the generated hash in the resulting string. Even if you hash the same password twice you'll get a different result each time.
This question already has answers here:
How to verify_password from a database
(2 answers)
Closed 3 years ago.
So I have a login page which worked fine without hashed passwords but of course, that wasn't secure so I decided to hash the passwords when registering.
but I don't know how and where should I use verify_password when I'm selecting the password from the database. I use while to see if there is a result with the username and password entered like this:
$q = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$x = $conn->query($q);
if ($x->num_rows > 0) {
while ($row = $x->fetch_assoc()) {
//Logged in seccesfully!
}
} else {
// Username or password is wrong!
}
password_hash() function can simplify our lives and our code can be secure. When you need to hash a password, just feed it to the function and it will return the hash which you can store in your database.
$hash = password_hash($password, PASSWORD_DEFAULT);
Now that you have seen how to generate hashes with the new API, let’s see how to verify a password. Remember that you store the hashes in a database, but it’s the plain password that you get when a user logs in.
The password_verify() function takes a plain password and the hashed string as its two arguments. It returns true if the hash matches the specified password.
<?php
if (password_verify($password, $hash)) {
// Success!
}
else {
// Invalid credentials
}
for more info read
This question already has answers here:
Secure hash and salt for PHP passwords
(14 answers)
Closed 5 years ago.
What is the best way to encrypt a password in Php. Codeigniter's documentation says that password should be hashed using php's Password Hashing extension. Until now i have been encrypting password's using encryption key of codeigniter. Any suggestions.
Use this is for password Hashing
<?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";
?>
Use this is for password Hashing Verify
<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
You can also use md5() function for password encryption and Decryption.
Here is the example :
$password = '123456789';
$encrypted_password = md5($password);
echo "Encrypted Password :".$encrypted_password;
-------------------
Output :
Encrypted Password : 25f9e794323b453885f5181f1b624d0b
Now to check entered password is correct or not ( for example login ) get stored md5 password from the database and you can check it this way.
$entered_password = '123456789';
$encrypted_password = md5($entered_password);
if($encrypted_password == $password){
echo "Success";
}else{
echo "Fail";
}
Basically, I've just started working with PHP, and am trying to get to grips with the password_hash function. When a user registers I hash their password using:
$hashed_password = password_hash($p, PASSWORD_DEFAULT);
Then, that hashed password is stored in my database. I then want to retrieve the password for login. So my code is written so that once the form is submitted, the email and password strings are sanitized, it the checks that they're not blank, once that's done, I take the user entered password, and hash it using:
$hash = password_hash($password, PASSWORD_DEFAULT);
Once again. Once this has done I connect to my DB, and try to select the user using:
$q = "SELECT * FROM users
WHERE email='$email' AND password='$hash'";
However. When debugging I've noticed that the user entered string, despite being the same as the string entered when signing up is different when hashed. so I've been echo'ing $hash and getting:
$2y$10$LQ55Q1DUqIgRx/2hgnbrnuQrYvrrBrq4WEFmV8TuxII6rDocaWzt2
but the exact same string "password" is stored in the db as:
$2y$10$omNPA7cviUm.6asuhJIJ8Or.m9WeHhJMkCqYYijel5g.NflbdVnV.
How do I get it so that when the user enters their password, it hashes the string and matches the one in the DB, so that they can log in? Am I missing something
Cheers
You'd need something like this:
$hashed_password = mysql_result(mysql_query("SELECT password FROM users WHERE email='$email'"));
$match = password_verify( $password, $hashed_password );
if($match){
echo 'Password is valid';
} else {
echo 'Password is not valid' ;
}
I have searched through Internet and found the function for hashing the password. But
i'm having trouble to deal with hashed password stored in the the database. the function i'm using generate the random password as it is concatenated with the random generated salt.
the problem comes when a user wants to change his password.
current_password = random hashed password( which must match the one stored in db).
if(current_password == $db_password){
enter new password
}
the above condition wont be true since the password is always random.
my function
function cryptPass($input,$rounds = 9) {
$salt = "";
$saltChars = array_merge(range('A','Z'),range('a','z'),range(0,9));
for($i = 0;$i < 22; $i++){
$salt .= $saltChars[array_rand($saltChars)];
}
return crypt($input,sprintf('$2y$%02d$', $rounds).$salt);
}
$pass = "password";
$hashedPass = cryptPass($pass);
echo $hashedPass;
i have 3 column in my user table (id, username, password).
can any one tell me how to properly use this function,
or is there a best way to do this?
You want to store the $salt generated in the database along with the hashed password. Then when you come to check the password you will be able to get the salt from the database and use it in the hashing process again.
So your database table with have an extra column in it called "salt"
(id, username, password, salt)
You need to do the same steps, as you would for the login. Check if the entered old password matches the password-hash in the database, then create a hash from the entered new password and store it.
PHP already has a function password_hash() to create a hash, and a function password_verify() to check whether the entered password matches the stored password-hash.
// 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);
So your code would look something like this:
if (password_verify(current_password, $db_password))
{
enter new password
}