I am trying to encrypt the given password to match one that is in a database. However using crypt() gives me a different result each time so it never matches. How can i make this work.
here is the statement that hashes the password given by the user.
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = crypt($_POST['password']);
prior to this i manually made a user that had the crypt('password') but if I enter 'password' into the field it doesn not match.
Try below:
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// get the hashed password from database
$hashed_password = get_from_db($username);
if (crypt($password, $hashed_password) == $hashed_password) {
echo "Password verified!";
}
}
Try like this,
//$pass_entered_from_login is the user entered password
//$crypted_pass is the encrypted password from the
//database or file
if(crypt($pass_entered_from_login,$crypted_pass)) == $crypted_pass)
{
echo("Welcome to my web site.")
}
Read more
crypt auto generates the salt each time you use it ............
so use the same salt for the user
do this while registering the user to your database and while checking tooo.
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = crypt($_POST['password'],$_POST['username']);
}
NOTE: the 2nd parameter is the salt in crypt function .
hope it helps :)
Related
I'm using PHP's password hashing API to hash and verify my passwords on a site I'm building, however whenever I try and verify my password it always returns false.
I have a User class which sets the password before they are inserted into the database:
public function set__password($passwd) {
self::$password = password_hash($passwd, PASSWORD_BCRYPT, array('cost' => 12));
}
If the username and email is unique the new user row is inserted - upon checking my database I have what seems to be a valid BCRYPT string for my password:
$2y$12$lTMEP0wevDEMX0bzStzoyOEzOTIAi3Hyhd3nYjGwzbI
To verify my password, I run the following script:
$username = $_POST['username'];
$password = $_POST['password'];
$DB = Database::getInstance();
// Get the stored password hash
$res = $DB->run__query('SELECT password FROM users WHERE username = "' . $username . '"');
$hash = $res[0]['password'];
// Do the passwords match?
if(password_verify($password, $hash)) {
echo 'success';
} else {
echo 'failed';
}
$hash pertains to the string quoted above, however when I then call password_verify($password, $hash) where $password is the plain-text password retrieved from my input field, I always receive a value of false.
The given hash string example has 50 characters instead of 60. Double-Check the database - CHAR(60) - and var_dump($hash).
Other problem that you can have, is when you reduce the cost in the server for gaining time.
Always use password_hash($pass, PASSWORD_DEFAULT), is the best way.
I have question about valid hashing passwords:
login.php
$login = $_POST['login'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);
if(!empty($login) && !empty($password) && password_verify(??){
I want to make secure login and I know that I have to verify the inputted password with existing hash (stored in database?). Also I know that bcrypt everytime makes new hash (because of different salt size etc).
The problem is that I don't know how to put this hash into database because I don't want to register new users, I have static list of users (exactly two: admin and user).
I tried manually copy/paste hash but it wouldn't work as I mentioned earlier that every time I run script new hash is created.
Can anyone help me how to put bcrypt hash in database (only once) so I can only check if inputted password is same as the one in database?
Do I need extra variables to store this hash?
EDIT:
login.php
<?php
session_start();
include("log.php");
include("pdo.php");
$login = $_POST['login'];
$password = $_POST['password'];
$adminHash = '$2y$10$lxPRtzzPDUZuPlodhU4QquP.IBrGpkjMNplpNgN9S1fEKd64tJ5vm';
$userHash = '$2y$10$Klt345wT66vA.4OAN5PEUeFqvhPQJ4Ua/A4Ylpc1ZcnJZv/hafgSu';
if(!empty($login) && !empty($password) && (password_verify($password, $adminHash) || password_verify($password, $userHash))){
$query = $pdo->prepare('SELECT * FROM xx WHERE login = ? AND admin = ?');
$query->execute(array( $login, 1));
$result = $query->fetchAll();
if(!empty($result)) {
$_SESSION['logged_admin'] = 1;
}
else {
$query->execute(array( $login, 0));
$result = $query->fetchAll();
if(!empty($result)) {
$_SESSION['logged_user'] = 1;
}
else {
$_SESSION['logged_error'] = 1;
}
}
}
else $_SESSION['logged_error'] = 1;
header("Location:index.php");
?>
it seems to be working but i dont know if it's best/safest solution.
With more passwords it will be too complicated i guess, still looking for best option!
What if i need more users? now every user have same hash and it's dangerous i get it, how to make it safe? generate hash for every user and make array or hashes?
You fetch first the one that has password_hash() from your database, and then compare it with password_verify($password, $storedpassword) like this : link
I've been trying to write a simple login for a couple of days now. After I'd thought I had it working, I realized that it would accept any input in the password field as being true so I scrapped it and started again. I'm trying to use the php function password_verify for the verification but no matter what I do, it always returns true still. Is there something I'm doing wrong? Here is my code (I know it's not secure, I just want it to recognize a wrong password for now)
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);
if(password_verify($_POST['password'], $hash))
{
echo 0;
}
else
{
echo 1;
}
}
The reason it always returns true is because you are verifying a hash that you just created... it will always be verified correctly.
When you use the password_verify() function the $hash parameter has to come from somewhere else (usually a database of some kind).
// If this is a POST request then handle the form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get password from form
$pass = filter_input(INPUT_POST, 'password', FILTER_UNSAFE_RAW);
// Connect to a database of some kind
// Get a previously hashed password
$hash = 'A HASH FROM SOMEWHERE ELSE...';
// Verify the previously hashed password
// against the password provided by the user
if (password_verify($pass, $hash)) {
echo 'Password is valid!';
}
}
You are $password getting a $_POST['password'];
You are hash a $password which is $_POST['password'];
password_verify($_POST['password'], $hash)
You are comparing a $_POST['password'] with a hash. the hash is also $_POST['password'].
That's why they return always true.because the $passwod,hash are $_POST['password'] is same.
You check the post password with the post password. You should check the post password instead with a wanted password.
You're assigning $hash to the password you received through POST.
This is how password_verify works
boolean password_verify ( string $password , string $hash )
Verifies that the given $hash matches the password received.
So now you're checking the password stored in $hash with the password obtained in POST which are the same.
Hence always true.
I'm using PHP's password hashing API to hash and verify my passwords on a site I'm building, however whenever I try and verify my password it always returns false.
I have a User class which sets the password before they are inserted into the database:
public function set__password($passwd) {
self::$password = password_hash($passwd, PASSWORD_BCRYPT, array('cost' => 12));
}
If the username and email is unique the new user row is inserted - upon checking my database I have what seems to be a valid BCRYPT string for my password:
$2y$12$lTMEP0wevDEMX0bzStzoyOEzOTIAi3Hyhd3nYjGwzbI
To verify my password, I run the following script:
$username = $_POST['username'];
$password = $_POST['password'];
$DB = Database::getInstance();
// Get the stored password hash
$res = $DB->run__query('SELECT password FROM users WHERE username = "' . $username . '"');
$hash = $res[0]['password'];
// Do the passwords match?
if(password_verify($password, $hash)) {
echo 'success';
} else {
echo 'failed';
}
$hash pertains to the string quoted above, however when I then call password_verify($password, $hash) where $password is the plain-text password retrieved from my input field, I always receive a value of false.
The given hash string example has 50 characters instead of 60. Double-Check the database - CHAR(60) - and var_dump($hash).
Other problem that you can have, is when you reduce the cost in the server for gaining time.
Always use password_hash($pass, PASSWORD_DEFAULT), is the best way.
I've made encrypting of the password in my register script and they are stored in the database, and I have to use them to login, so I would want to use the unencrypted ones to login. I've read some of the threads in here but nothing is helping me. How can I add it in my login.php? The salt is also stored in the database.
This is my register.php script for encrypting
$hash = hash('sha256', $password1);
function createSalt()
{
$text = md5(uniqid(rand(), TRUE));
return substr($text, 0, 3);
}
$salt = createSalt();
$password = hash('sha256', $salt . $hash);
and this is my login.php with season
//Create query
$qry="SELECT * FROM member WHERE username='$username' AND password='$password'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) > 0) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['id'];
$_SESSION['SESS_FIRST_NAME'] = $member['username'];
$_SESSION['SESS_LAST_NAME'] = $member['password'];
session_write_close();
header("location: profile.php");
exit();
}
else {
//Login failed
//error message
}
else {
die("Query failed");
}
These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.
Read the php documentation to find out about the possibilities and best practices:
http://www.php.net/manual/en/function.password-hash.php
Save a password hash:
$options = [
'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];
$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);
// Now insert it (with login or whatever) into your database, use mysqli or pdo!
Get the password hash:
// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;
if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
According to php.net the Salt option has been deprecated as of PHP 7.0.0, so you should use the salt that is generated by default and is far more simpler
Example for store the password:
$hashPassword = password_hash("password", PASSWORD_BCRYPT);
Example to verify the password:
$passwordCorrect = password_verify("password", $hashPassword);
array hash_algos(void)
echo hash('sha384', 'Message to be hashed'.'salt');
Here is a link to reference http://php.net/manual/en/function.hash.php
You couldn't login because you did't get proper solt text at login time.
There are two options, first is define static salt, second is if you want create dynamic salt than you have to store the salt somewhere (means in database) with associate with user.
Than you concatenate user solt+password_hash string now with this you fire query with username in your database table.
I think #Flo254 chained $salt to $password1and stored them to $hashed variable. $hashed variable goes inside INSERT query with $salt.
You can't do that because you can not know the salt at a precise time. Below, a code who works in theory (not tested for the syntaxe)
<?php
$password1 = $_POST['password'];
$salt = 'hello_1m_#_SaLT';
$hashed = hash('sha256', $password1 . $salt);
?>
When you insert :
$qry="INSERT INTO member VALUES('$username', '$hashed')";
And for retrieving user :
$qry="SELECT * FROM member WHERE username='$username' AND password='$hashed'";