Migrate from SHA256 hashed passwords to BCRYPT in PHP7+MySQL - php

I have an old web application with a few users registered that is using the unsecure hash("sha256", trim($_POST["password"])) to store the hashed password in MySQL database. Now I want to update the web application to use the more secure BCRYPT password_hash() however I don't want to email all registered users alerting them to change their password. So I was thinking on implementing BCRYPT on the sha256() hashed password this way:
To save the password I will sha256() hash the user's password:
$hashed_password = password_hash(hash("sha256", trim($_POST["password"])), PASSWORD_BCRYPT);
Then I will save the BCRYPT hashed password in the database.
And to verify the user's password I would simply do this:
$hashed_password = "select hashed_password from users where email = 'abc#email.com'";
if(password_verify(hash("sha256", trim($_POST["password"])), $hashed_password))
{
echo "Welcome";
}
else
{
echo "Wrong Password!";
}
This way I will just update the user's password in the MYSQL database by looping each registered user, then I will retrieve the sha256() hashed password, and finally I will just re-save it after it has been BCRYPTed with password_hash():
$new_password = password_hash($old_sha256_hashed_password, PASSWORD_BCRYPT);
$mysql->save_user_password($new_password, $user_id);
So users will still be able to login with their old password.
What do you think about this solution?
Is it still safe even if I sha256() hash the password before BCRYPT it?

Since your current hashing system (unsalted SHA256) is indeed very unsecure, you could give immediate protection to the passwords with double hashing. As soon as possible, when the user logs in the next time, I would switch to the new algorithm and remove double hashing.
Make old hashes more secure:
$doubleHashToStoreInDb = password_hash($oldUnsaltedSha256HashFromDb, PASSWORD_DEFAULT);
Doing this for each row will protect the otherwise unsecurely stored passwords. Note the PASSWORD_DEFAULT parameter, it should be prefered over a specific algorithm, because it is future proof. And mark the double hashes, so you can distinguish between double hashes and already converted hashes, see why.
Handle new user registrations:
$hashToStoreInDb = password_hash($_POST['password'], PASSWORD_DEFAULT);
Just use the new algorithm without double hashing.
Verify logins:
if (checkIfDoubleHash($storedHash))
{
$correctPassword = password_verify(oldPasswordHash($_POST["password"]), $storedHash);
if ($correctPassword)
storeConvertedHash(password_hash($_POST['password'], PASSWORD_DEFAULT));
}
else
{
$correctPassword = password_verify($_POST['password'], $storedHash);
}
// Hashes the user password with a deprecated hashing scheme
function oldPasswordHash($password)
{
return hash("sha256", trim($password));
}
Double hashes will be converted to the new password hash function, this is possible because we have the original user password at this moment. New hashes are verified with password_verify() which is a future proof and backwards compatible function.
Adapting the password algorithm to future hardware is not a one-time task, it will be necessary as soon as new hardware will become faster. PHP offers the function password_needs_rehash() to find out whether a rehashing is necessary, then you can also calculate a new hash and store it.

Related

PHP: How to retrieve original value from hashed / encrypted email address [duplicate]

I need to decrypt a password. The password is encrypted with password_hash function.
$password = 'examplepassword';
$crypted = password_hash($password, PASSWORD_DEFAULT);
Now, let's assume that $crypted is stored in a database (there's a "users" table, with usernames, passwords, etc) and I need to do a login: I have to see if the password entered by the user matches the encrypted password stored in the database.
This is the sql code...
$sql_script = 'select * from USERS where username="'.$username.'" and password="'.$inputpassword.'"';
...but $inputpassword is not encrypted, so it's not equal to what is stored in the password field of the table users...
So, there's a function to decrypt after the use of password_hash? Or should I change my encrypt method? Or what else?
Bcrypt is a one-way hashing algorithm, you can't decrypt hashes. Use password_verify to check whether a password matches the stored hash:
<?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.';
}
In your case, run the SQL query using only the username:
$sql_script = 'SELECT * FROM USERS WHERE username=?';
And do the password validation in PHP using a code that is similar to the example above.
The way you are constructing the query is very dangerous. If you don't parameterize the input properly, the code will be vulnerable to SQL injection attacks. See this Stack Overflow answer on how to prevent SQL injection.
The passwords cannot be decrypted as will makes a vulnerability for users. So, you can simply use password_verify() method to compare the passwords.
if(password_verify($upass, $userRow['user_pass'])){
//code for redirecting to login screen }
where, $upass is password entered by user and $userRow['user_pass'] is user_pass field in database which is encrypted by password_hash() function.
I need to decrypt a password. The password is crypted with
password_hash function.
$password = 'examplepassword';
$crypted = password_hash($password, PASSWORD_DEFAULT);
Its not clear to me if you need password_verify, or you are trying to gain unauthorized access to the application or database. Other have talked about password_verify, so here's how you could gain unauthorized access. Its what bad guys often do when they try to gain access to a system.
First, create a list of plain text passwords. A plain text list can be found in a number of places due to the massive data breaches from companies like Adobe. Sort the list and then take the top 10,000 or 100,000 or so.
Second, create a list of digested passwords. Simply encrypt or hash the password. Based on your code above, it does not look like a salt is being used (or its a fixed salt). This makes the attack very easy.
Third, for each digested password in the list, perform a select in an attempt to find a user who is using the password:
$sql_script = 'select * from USERS where password="'.$digested_password.'"'
Fourth, profit.
So, rather than picking a user and trying to reverse their password, the bad guy picks a common password and tries to find a user who is using it. Odds are on the bad guy's side...
Because the bad guy does these things, it would behove you to not let users choose common passwords. In this case, take a look at ProCheck, EnFilter or Hyppocrates (et al). They are filtering libraries that reject bad passwords. ProCheck achieves very high compression, and can digest multi-million word password lists into a 30KB data file.
Use the password_verify() function
if (password_vertify($inputpassword, $row['password'])) {
print "Logged in";
else {
print "Password Incorrect";
}
it seems someone finally has created a script to decrypt password_hash.
checkout this one: https://pastebin.com/Sn19ShVX
<?php
error_reporting(0);
# Coded by L0c4lh34rtz - IndoXploit
# \n -> linux
# \r\n -> windows
$list = explode("\n", file_get_contents($argv[1])); # change \n to \r\n if you're using windows
# ------------------- #
$hash = '$2y$10$BxO1iVD3HYjVO83NJ58VgeM4wNc7gd3gpggEV8OoHzB1dOCThBpb6'; # hash here, NB: use single quote (') , don't use double quote (")
if(isset($argv[1])) {
foreach($list as $wordlist) {
print " [+]"; print (password_verify($wordlist, $hash)) ? "$hash -> $wordlist (OK)\n" : "$hash -> $wordlist (SALAH)\n";
}
} else {
print "usage: php ".$argv[0]." wordlist.txt\n";
}
?>

Calling back a crypted password?

I hashed my password into the database using the crypt() function.
$cryptpass = crypt($user_pass);
Now when i try to login in with my password that is "test" it wont work.
Here is the PHP from login
$user_name = mysql_real_escape_string($_POST['user_name']);
$user_pass = crypt($_POST['user_pass']);
$user_level = mysql_real_escape_string($_POST['user_level']);
$encrypt = md5($user_pass);
$admin_query = "select * from admin_login where user_name='$user_name' AND user_pass='$user_pass' AND user_level='$user_level'";
Sorry i am kinda new to password hashing , in the whole time i saved my passwords as plain texts.
EDIT: When i echo the query here are the results
crypt = $1$vh4.Mq4.$YaABh9aqRKbKpACTDApWb1 ,select * from admin_login where user_name='testcr' AND user_pass='$1$vh4.Mq4.$YaABh9aqRKbKpACTDApWb1' AND user_level='a' ,the real password is "test" .
You have choosen an extremely unsafe way to store the passwords (DES and MD5 hash without salting). You should think about using PHP's function password_hash(), to create a BCrypt hash.
For verification you will first have to get the hash from the database by username, afterwards you can verify the password with password_verify(). Directly verifying the hash with an SQL query is not possible because of the salt.
// 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);
If you are interested to read more about this topic, have a look at my tutorial about safely storing passwords.
Try debugging your SQL statement.
$admin_query = "select * from admin_login where user_name='$user_name' AND user_pass='$user_pass' AND user_level='$user_level'";
echo $admin_query;
Run the query in your SQL engine and see if you can spot the differences.

How can I decrypt a password hash in PHP?

I need to decrypt a password. The password is encrypted with password_hash function.
$password = 'examplepassword';
$crypted = password_hash($password, PASSWORD_DEFAULT);
Now, let's assume that $crypted is stored in a database (there's a "users" table, with usernames, passwords, etc) and I need to do a login: I have to see if the password entered by the user matches the encrypted password stored in the database.
This is the sql code...
$sql_script = 'select * from USERS where username="'.$username.'" and password="'.$inputpassword.'"';
...but $inputpassword is not encrypted, so it's not equal to what is stored in the password field of the table users...
So, there's a function to decrypt after the use of password_hash? Or should I change my encrypt method? Or what else?
Bcrypt is a one-way hashing algorithm, you can't decrypt hashes. Use password_verify to check whether a password matches the stored hash:
<?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.';
}
In your case, run the SQL query using only the username:
$sql_script = 'SELECT * FROM USERS WHERE username=?';
And do the password validation in PHP using a code that is similar to the example above.
The way you are constructing the query is very dangerous. If you don't parameterize the input properly, the code will be vulnerable to SQL injection attacks. See this Stack Overflow answer on how to prevent SQL injection.
The passwords cannot be decrypted as will makes a vulnerability for users. So, you can simply use password_verify() method to compare the passwords.
if(password_verify($upass, $userRow['user_pass'])){
//code for redirecting to login screen }
where, $upass is password entered by user and $userRow['user_pass'] is user_pass field in database which is encrypted by password_hash() function.
I need to decrypt a password. The password is crypted with
password_hash function.
$password = 'examplepassword';
$crypted = password_hash($password, PASSWORD_DEFAULT);
Its not clear to me if you need password_verify, or you are trying to gain unauthorized access to the application or database. Other have talked about password_verify, so here's how you could gain unauthorized access. Its what bad guys often do when they try to gain access to a system.
First, create a list of plain text passwords. A plain text list can be found in a number of places due to the massive data breaches from companies like Adobe. Sort the list and then take the top 10,000 or 100,000 or so.
Second, create a list of digested passwords. Simply encrypt or hash the password. Based on your code above, it does not look like a salt is being used (or its a fixed salt). This makes the attack very easy.
Third, for each digested password in the list, perform a select in an attempt to find a user who is using the password:
$sql_script = 'select * from USERS where password="'.$digested_password.'"'
Fourth, profit.
So, rather than picking a user and trying to reverse their password, the bad guy picks a common password and tries to find a user who is using it. Odds are on the bad guy's side...
Because the bad guy does these things, it would behove you to not let users choose common passwords. In this case, take a look at ProCheck, EnFilter or Hyppocrates (et al). They are filtering libraries that reject bad passwords. ProCheck achieves very high compression, and can digest multi-million word password lists into a 30KB data file.
Use the password_verify() function
if (password_vertify($inputpassword, $row['password'])) {
print "Logged in";
else {
print "Password Incorrect";
}
it seems someone finally has created a script to decrypt password_hash.
checkout this one: https://pastebin.com/Sn19ShVX
<?php
error_reporting(0);
# Coded by L0c4lh34rtz - IndoXploit
# \n -> linux
# \r\n -> windows
$list = explode("\n", file_get_contents($argv[1])); # change \n to \r\n if you're using windows
# ------------------- #
$hash = '$2y$10$BxO1iVD3HYjVO83NJ58VgeM4wNc7gd3gpggEV8OoHzB1dOCThBpb6'; # hash here, NB: use single quote (') , don't use double quote (")
if(isset($argv[1])) {
foreach($list as $wordlist) {
print " [+]"; print (password_verify($wordlist, $hash)) ? "$hash -> $wordlist (OK)\n" : "$hash -> $wordlist (SALAH)\n";
}
} else {
print "usage: php ".$argv[0]." wordlist.txt\n";
}
?>

Comparing hash value of password in PHP

As part of learning php, I wanted to try a register and login page, however, the site I'm following for how to store a password uses MySQLI and I'm not using that:
Hashing the password
$password1 = 'hello123';
// A higher "cost" is more secure but consumes more processing power
$cost = 10;
// Create a random salt
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
// Prefix information about the hash so PHP knows how to verify it later.
// "$2a$" Means we're using the Blowfish algorithm. The following two digits are the cost parameter.
$salt = sprintf("$2a$%02d$", $cost) . $salt;
// Value:
// $2a$10$eImiTXuWVxfM37uY4JANjQ==
// Hash the password with the salt
$hash = crypt($password1, $salt);
I'm stuck on retrieving the password however, here's the site's code for it:
$username = 'Admin';
$password = 'gf45_gdf#4hg';
$sth = $dbh->prepare('
SELECT
hash
FROM users
WHERE
username = :username
LIMIT 1
');
$sth->bindParam(':username', $username);
$sth->execute();
$user = $sth->fetch(PDO::FETCH_OBJ);
// Hashing the password with its hash as the salt returns the same hash
if ( crypt($password, $user->hash) === $user->hash ) {
// Ok!
}
From what I can see, he grabs the hash value of the password for the user in the DB and compares the password that was passed using the hash and check with the one in the DB.
I've been trying this but the result hash is never the same as the original one:
$pwdtocheck = 'hello123';
// no call do DB yet, doing this on the same page after hashing, the $hash is the same as above
$pwdhash = crypt($pwdtocheck, $hash);
// if I echo $pwdhash it's never exactly the same as the $hash.
if ( $pwdhash === $hash) {
echo "same pwd";
}
I cannot see the actual problem in your code, maybe your database field is smaller than 60 characters, or you are comparing different passwords. In every case there is an easier and safer way to hash passwords, just use the new functions password_hash() and password_verify(). There exists also a compatibility pack for earlier PHP versions.
// 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);
EDIT:
I see now that you are using a salt when you compare the passwords. In your line:
$pwdhash = crypt($pwdtocheck, $hash);
the $hash variable has the salt prepended to it because crypt() will automatically do that for you. crypt() will extract the salt from the $hash because it knows the expected length of the salt based on the algorithm used. See the documentation.
I'll keep my original answer below for context and for those looking for a similar answer.
END EDIT
The password is not the same for you because you are using a salt when you originally hash the password to put in your database, but you are not salting the password later when you check against the database.
You should use the same salt string when you save the password as when you check the user's password on login. Usually, you will randomly generate the salt string for each password (as you are doing) and then save the salt string to the database along with the hashed password (either in the same column or its own column) so that you can use the same salt to check the user's password on login.
See https://crackstation.net/hashing-security.htm#salt for reference.
I can't access the article you're referencing but I imagine:
You need to check using the salt as the salt and not the hash.
crypt($pwdtocheck, $user->salt) == $user->hash
should work

How do you verify a password with PHP/MySQL using BCRYPT

I don't understand how this works
$hash = $bcrypt->hash($_POST['password']); //this string is stored in mysql
Then when a user logs in,
//get hash string from above from mysql, then
if ($bcrypt->verify($_POST['password'], $row['password'])) {
echo "Logged in.";
}
A.) Am I doing this correctly?
B.) If so, how does bcrypt remember the salt if it's not stored in the database?
The salt is prepended to the hash, and so the the function pulls the salt out of the hash from the database. This is why you have to pass the hash from the database to the verification function, instead of just rehashing the password and comparing them.
And yeah, it does look like you are doing it correctly.

Categories