Yii2 - generated password hash different every time - php

I'm trying to use Yii's generatePasswordHash() function, but I get a different hash with the same password, every time.
$this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);
Here 3 hashes created with the password "test":
$2y$13$wsvC4i8YMwKKHJ2K5iYRG.Z0KBetOh3BctVpJN5pVkXGOcW85hRkO ,
$2y$13$QfV2Qxlj4F5gUh1wIL2WUewoZ55CKYKevjRmRqrenxq8L5ym5xX9. ,
$2y$13$rDArvLa8hnpDGiiDdCs7be4iTsr2T3XMXmnapynuD1i1ekbz8zF4m
Anyone an idea what's happening?
EDIT:
When I try to verify with:
Yii::$app->getSecurity()->validatePassword($password, $this->password)
it returns false.
EDIT#2:
function looks like this:
public function validatePassword($password)
{
return Yii::$app->getSecurity()->validatePassword($password, $this->password);
}
$password is the input password and $this->password is the hash.
Strangely password_verify($password, $this->password) works, but Yii's verifier doesn't.

All hashes are correct. Because hash algorithms make different hashes for the same password. Where does the password variable come from in your code? It should be a password string not a hash.
$hash = "hashed version";
$password = "string password";
if (Yii::$app->getSecurity()->validatePassword($password, $hash)){
// password correct
}

Adding to efendi's answer.
Getting a different hash each time Yii's generatePasswordHash() function is run is normal behavour.
Validating the password against the hash requires the 'salt' from the 'hash'.
The first 22 characters after '$2y$13$' in the hash is the salt.
The validatePassword($password, $hash) function gets the salt from the hash, hashes the $password using the salt which should get the same hash as the $hash if the password were to be correct.

Related

sha1() for Password hashing

I am using sha1 for my password security. I have stored password in this way in register.php
// secure password
$salt = openssl_random_pseudo_bytes(20);
$secured_password = sha1($password . $salt);
//Send it to mysql table
$result = $access->registerUser($username, $secured_password, $salt, $email, $fullname);
This all is working fine.
Problem is here:
In my login.php
$password = htmlentities($_POST["password"]);
$secure_password = $user["password"];
$salt = $user["salt"];
// 4.2 Check if entered passwords match with password from database
if ($secure_password == sha1($password . $salt)) {
//do something
} else {
//do something
}
I am always getting as password does not match.
where am I going wrong?
First is first. NEVER USE SHA OR MCRYPT TO STORE YOUR PASSWORD.
EDIT : The password_hash() function generates a long password hash, so make sure that your column in the mysql is a VARCHAR of 500 space
All these useless practises is the root reason why almost many websites get hacked. To tackle the situation, php did a lot of research and then at last came with the most secure function called the password_hash(). I am not more onto explaining about password_hash() here as there are already many documents on the internet.
You can always hash a password like this
<?php
$securePassword = password_hash($_POST['password'], PASSWORD_DEFAULT);
$query = $db->query('INSERT INTO users ......');
?>
And, to verify the password, you can simply use this function
<?php
$passwordHash = $query['password']; //Password from database
$userPassword = $_POST['password']; //Password from form
if(password_verify($userPassword, $passwordHash)) {
echo 'Password is correct, logged in!';
} else {
echo 'Password is wrong, try again';
}
?>
And, answer for your question.
PLEASE DON'T USE SHA OR MCRYPT OR BCRYPT. IF YOU WANNA GET YOUR WEBSITE HACKED, THEN CONTINUE. OR USE password_hash()
The reason you don't get the hash genereated each time because the openssl_random_pseudo_bytes() generates random numbers each time. So each time, during execution, the function returns different numbers and you get your sha result wrong and thus giving a FALSE alert.
PLEASE, AGAIN. I BEG YOU TO USE password_hash() FUNCTION
For more information on password_hash() and password_verify() :
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php

How to verify an hashed password

I am using the password_hash() function.
Now it works to hash the password, but how do I verify it?
Well the function for this option is called: password_verify.
How it does work is this;
<?php
$password = "[PASS]"; //Password user fill in.
$hash= "[HASH]"; //The hashed password that you saved.
$checkPass = password_verify($password, $hash); //This returns a boolean; true or false
if ($checkPass == true)
{
echo 'Password is good!';
}
else
{
echo 'Password is wrong!';
}
?>
boolean password_verify ( string $password , string $hash )
Verifies that the given hash matches the given password.
Note that password_hash() returns the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it. This allows the verify function to verify the hash without needing separate storage for the salt or algorithm information.
password
The user's password.
hash
A hash created by password_hash()
http://php.net/manual/en/function.password-verify.php

Trouble validating md5 hashed password with randomly generated salt?

I realize this is not as secure as it could be, but I want to do it this way.
I have this code which generates the password from a user's entry ($password)...
$salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$new_password = md5($salt . $password);
$new_password = $salt . $new_password;
This is how I'm trying to check against the saved password:
$split_salt = substr($saved_password, 0, 22);
$incomplete_password = md5($split_salt . $current_password);
$hashed_password = $split_salt . $incomplete_password;
if ($saved_password != $hashed_password) {
$error = "error";
} else {
//Validated
}
As far as I can tell this should work. However, I'm getting the error instead of the validation. Does this have something to do with MCRYPT not producing exactly 22 characters?
I know this is not what you want to hear, but your scheme is so utterly unsafe and a good solution is so simple to implement, that you should reconsider:
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_DEFAULT);
// 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);
Your actual problem is the salt, mcrypt_create_iv() will return a binary string and it can very well contain \0 characters. So it is pure luck if your approach works or not.

hashing password with salt

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
}

Sending forgot password emails using blowfish

This is stored in a database. How do I send this demo password to my user? I cant convert this ($2y$10$Zjk5YzQ4ZTlhMzNlNTUzMO3Wnm1FqXmAb6/4DmyptNGoEdWGLwls.) to normal text.
Is there any solution? I'm also unable to send random password.
demo = $2y$10$Zjk5YzQ4ZTlhMzNlNTUzMO3Wnm1FqXmAb6/4DmyptNGoEdWGLwls.
Here are some functions I used for password checking and generation:
function password_encrypt($password) {
$hash_format = "$2y$10$"; // Tells PHP to use Blowfish with a "cost" of 10
$salt_length = 22; // Blowfish salts should be 22-characters or more
$salt = generate_salt($salt_length);
$format_and_salt = $hash_format . $salt;
$hash = crypt($password, $format_and_salt);
return $hash;
}
function generate_salt($length) {
// Not 100% unique, not 100% random, but good enough for a salt
// MD5 returns 32 characters
$unique_random_string = md5(uniqid(mt_rand(), true));
// Valid characters for a salt are [a-zA-Z0-9./]
$base64_string = base64_encode($unique_random_string);
// But not '+' which is valid in base64 encoding
$modified_base64_string = str_replace('+', '.', $base64_string);
// Truncate string to the correct length
$salt = substr($modified_base64_string, 0, $length);
return $salt;
}
function password_check($password, $existing_hash) {
// existing hash contains format and salt at start
$hash = crypt($password, $existing_hash);
if ($hash === $existing_hash) {
return true;
} else {
return false;
}
}
It is not a good scheme for password recovery, to generate a new password and send it to the user. Instead send the user a link with a random independend code, and store this code in your database (hashed). When the user clicks the link, then let him enter a new password. There is no need to know the old password then, the user is authenticated when he can read the email (his email address).
A forgotten password form, can be posted by everybody: You wouldn't be happy if somebody entered your email, and your password was changed immediately. Retrieving the link, you have the opportunity to either ignore the email, or to confirm that you really want to change the password.
As you correctly pointed out, passwords should be stored as hash, and therefore cannot be retrieved. As soon as the hash of the password is stored in the database, there should be no further need to know the real password. Whenever you need the password later, you will know it, because the user entered it.
To generate the BCrypt hash, i would recommend to use the PHP function password_hash(), there exists also a compatibility pack for earlier PHP versions. Especially the generation of the salt is solved much better there.
P.S.
The hash you described is called BCrypt, it is based on the blowfish cipher which is used for two-way encryption.

Categories