What is a solid approach to change passwords in PHP? - php

My script is supposed work like that:
Insert the Old password and
then the New Passsword.
The old password is working and checked but when i insert the new password the code no work... without errors, nothing...
Here is the code I have so far:
$user_p = $_SESSION['user']['username'];
if(empty($_SESSION['user']))
{
header("Location: live.php");
die("Redirecting to live.php");
}
if(!empty($_POST))
{
$currentPassword = preg_replace('/\s+/', '', $_POST['currentPassword']);
$newPassword = preg_replace('/\s+/', '', $_POST['newPassword']);
$oldpass = IrBuscarPassword($_SESSION['user']['username']);
$saltcode = IrBuscarSalt($_SESSION['user']['username']);
$formEncriptedPass = hash('sha256', $currentPassword . $saltcode);
for($round = 0; $round < 65536; $round++)
{
$formEncriptedPass = hash('sha256', $formEncriptedPass . $saltcode);
}
$changepass = False;
if($oldpass != $formEncriptedPass)
{
echo "Password NO-OK.";
//die();
}
else
{
if($newPassword == '')
{
$_SESSION['error'] = " The field E-mail is empty.</span></div>";
}
else
{
if($newPassword == '' || !isset($newPassword))
{
$changepass = False;
}
else
{
$changepass = True;
atualizarMail($newPassword, $_SESSION['user']['username']);
}
}
}
if(!isset($currentPassword) || ($currentPassword == ''))
{
$_SESSION['error'] = " The Password field is empty.</span></div>";
}
$password = hash('sha256', $_POST['currentPassword'] . $saltcode);
if($changepass == False)
{
$_SESSION['error'] = "<br/>New Password.</span></div>";
}
if($_POST['newPassword'] != $_SESSION['user']['username'])
{
$query = "
SELECT
1
FROM users
WHERE
password = :newPassword
";
$query_params = array(
':newPassword' => $_POST['newPassword']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
}
if(!empty($_POST['newPassword']))
{
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['newPassword'] . $salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password . $salt);
}
}
else
{
$password = null;
$salt = null;
}
if(isset($_SESSION['error']))
{
echo $_SESSION['error'];
$_SESSION['error'] = null;
}
else
{
$_SESSION['user']['password'] = $_POST['newPassword'];
$_SESSION['success'] = " The password has been successfully changed..</span></div>";
header("Location: password.php");
die("Redirecting to logout.php");
}
}
Can someone help me?

Your code has many problems and is difficult to read/understand. Some examples:
You check for the same things again and again if($newPassword == '')
You do different things in one function atualizarMail()
Your hash function is unsafe and not future proof. It is implemented in at least 3 places. Storing the salt could be done much easier.
Passwords should not be sanitized, only validated (no preg_replace())
The line if($_POST['newPassword'] != $_SESSION['user']['username']) doesn't make much sense.
There are too many levels of if statements, combined with using states $changepass (hard to read, easy to do a mistake)
The query SELECT 1 FROM users WHERE password = :newPassword will hopefully never fetch any data, because only the hash is stored in the database.
I hope i could point out, why i recommend to start from scratch, after reading a good tutorial. Maybe i can give you some ideas to start width:
// 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);
The second function password_verify() can be used for login as well as to check if the old password matches.
Another tip, validate all input at the start of your script and redirect immediately if there are any problems. After doing validation, do not check again for invalid input, just use it.

Related

PHP MySQL PDO Login / Registration system over PBKDF2 Encryption won't log in

I am working with a specific encryption ( PBKDF2 ) for some reasons.
I am now building the website and I am having an issue with the Log In system.
The Registration page works perfectly has desired.
I don't have any output of errors when I try to log in and still the password does not match.
Here is my registration.php :
<?php
require '../global.php';
$pdo = New Database();
$account->IPisBanned($_SERVER['REMOTE_ADDR']);
$account->isConnected();
if(!empty($_POST['username']) AND !empty($_POST['email']) AND !empty($_POST['password']) AND !empty($_POST['password_confirmation'])) {
$bdd = $pdo->query('SELECT id FROM users WHERE username = ?', [$core->F_HTML($_POST['username'])]);
if($bdd->rowCount() == 0) {
if(preg_match('`^([a-zA-Z0-9-=?!#]{3,15})$`', $core->F_HTML($_POST['username']))) {
$bdd2 = $pdo->query('SELECT id FROM users WHERE email = ?', [$core->F_HTML($_POST['email'])]);
if($bdd2->rowCount() == 0) {
if(filter_var($core->F_HTML($_POST['email']), FILTER_VALIDATE_EMAIL)) {
if($_POST['password'] == $_POST['password_confirmation']) {
if(strlen($_POST['password']) >= 6 AND strlen($_POST['password_confirmation']) >= 6) {
$iterations = 10000;
$length = 40;
$secret = "at_least_16_byte";
$salt = $secret.$_POST['username'];
$hash = hash_pbkdf2("sha1", $_POST['password'], $salt, $iterations, $length);
$hash = strtoupper($hash);
$bdd3 = $pdo->query('INSERT INTO users (username, password, mail, account_created, ip_reg) VALUES (?, ?, ?, ?, ?)', [$core->F_HTML($_POST['username']), $core->F_HTML($hash), $core->F_HTML($_POST['email']), time(), $_SERVER['REMOTE_ADDR']]);
$_SESSION['id'] = $pdo->lastInsertId();
echo 'success';
} else {
echo 'Passwords does not match.';
}
} else {
echo 'Password too short.';
}
} else {
echo 'Invalid email address.';
}
} else {
echo 'This Email is already used by another account.';
}
} else {
echo 'Invalid username.';
}
} else {
echo 'Username already in use.';
}
} else {
echo 'Required fields are emtpy.';
}
?>
And here is my login.php :
<?php
require '../global.php';
$pdo = New Database();
$account->IPisBanned($_SERVER['REMOTE_ADDR']);
$account->isConnected();
if(!empty($_POST['username']) AND !empty($_POST['password'])) {
$bdd = $pdo->query('SELECT * FROM users WHERE username = ?', [$core->F_HTML($_POST['username'])]);
$iterations = 10000;
$length = 40;
$secret = "at_least_16_byte";
$salt = $secret.$_POST['username'];
$hash = hash_pbkdf2("sha1", $_POST['password'], $salt, $iterations, $length);
$hash = strtoupper($hash);
if($bdd->rowcount() == 1) {
$req = $bdd->fetch();
if(password_verify($hash, $req['password'])) {
$account->UserisBanned($core->F_HTML($_POST['username']));
$_SESSION['id'] = $req['id'];
$account->Update($_SESSION['id']);
echo 'success';
} else {
echo 'The password is incorrect.';
}
} else {
echo 'The username does not exist.';
}
} else {
echo 'The required fields are empty.';
}
?>
I am strongly confused, I spent hours trying to fix this but I really can't. Thank you for your time :)
It seems that password_verify expects the first param to be the user's plain text password.
Try this:
password_verify($_POST['password'], $req['password'])
NOTE: this means you probably need to drop the strtoupper as well.
https://www.php.net/manual/en/function.password-verify.php
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.
/**
* (PHP 5 >= 5.5.0, PHP 5)<br/>
*
* Checks if the given hash matches the given options.
* #link https://secure.php.net/manual/en/function.password-verify.php
* #param string $password The user's password.
* #param string $hash A hash created by password_hash().
* #return boolean Returns TRUE if the password and hash match, or FALSE otherwise.
* #since 5.5.0
*/
function password_verify ($password, $hash) {}
If you dont want to do that, you could drop the password_verify and do:
`if ($hash === $req['password'])`
#!/usr/local/bin/php
<?php
//================================================================
//PBKDF2 generator for PBKDF2 hashed password log in.eg, mosquitto auth-plug
// I got this generator from somewhere online.. credit go to original writer..
// I research again and again to got loging in Mosquitto server.
// Use this generator to generate password earlier or use in register.php
function password_hash($password, $salt = '', $algo = 'sha256', $iterations = 901, $key_len = 24, $salt_len = 12)
{
//salt len is 12 , ajust your own
$salt = 'pN94c3+KCcNvIV1v'; //I added for my own, to use php login. salt is need to be contant all the time
if($salt=='') $salt = base64_encode(openssl_random_pseudo_bytes($salt_len));
$key = base64_encode(openssl_pbkdf2($password, $salt, $key_len, $iterations, $algo));
return sprintf("PBKDF2$%s$%d$%s$%s\n",
$algo,
$iterations,
$salt,
$key);
}
$password = trim($argv[1]);
if(function_exists('readline'))
{
while($password=='')
{
$password = trim(readline('Enter password: '));
}
}
else
{
$handle = fopen ("php://stdin","r");
while($password=='')
{
echo 'Enter password: ';
$password = trim(fgets($handle));
echo chr(10);
}
fclose($handle);
}
echo 'PBKDF2 password generator for Mosquitto auth plugin [https://github.com/jpmens/mosquitto-auth-plug]',chr(10);`enter code here`
echo 'Encoding password = ',$password,chr(10);
echo mqtt_hash($password),chr(10);
?>
//==========================================================================
// and verify with this pattern in login.php and register php
// I wrote php script to use above sample function
// php code
<?php
include 'get_hash.php';
$username = $_GET['username'];
$plain_password = $_GET['password'];
$password = trim(get_hash($plain_password)); //trim white space
$Sql_Query = "select * from tblusers where username = '$username'";
$result = mysqli_query($con,$Sql_Query);
if (mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_assoc($result);
if ($password == $row['pw']){
$status = "ok";
}
else
{
$status = "failed";
}
}
?>
get_hash.php
<?php
// can use login.php and register.php
function get_hash($password, $salt = '', $algo = 'sha256', $iterations = 901, $key_len = 24, $salt_len = 12)
{
$salt = 'pN94c3+KCcNvIV1v';
if($salt=='') $salt = base64_encode(openssl_random_pseudo_bytes($salt_len));
$key = base64_encode(openssl_pbkdf2($password, $salt, $key_len, $iterations, $algo));
return sprintf("PBKDF2$%s$%d$%s$%s\n",
$algo,
$iterations,
$salt,
$key);
}
?>

PHP - password_hash() verification

The following code should be straight forward and simple, the insert into the db on signup creates a hash, but later when I try to login with the same password the hash it is creating isn't matching up to what is in the database (I had print_r's throughout to verify). Can someone see if I'm just overlooking something dumb?
session_start();
require_once("login.php");
$error = "";
$email = "";
$password = "";
if (isset($_GET['logout'])) {
unset($_SESSION['id']);
setcookie('id', '', time() - 60*60);
$_COOKIE['id'] = "";
} else {
if (isset($_SESSION['id']) or isset($_COOKIE['id'])) {
header("Location: loggedinpage.php");
}
}
if (isset($_POST["submit"])) {
$link = mysqli_connect($hn, $un,$pw,$db);
if($link->connect_error) die("Fatal Errror.");
if (!$_POST["email"]) {
$error .="An email address is required<br>";
}
if (!$_POST["password"]) {
$error .="A password address is required<br>";
}
if ($error != "") {
$error= "<p>There were error(s) in your form:</p>".$error;
} else {
if ($_POST['signup'] == 1) {
$email = mysqli_real_escape_string($link, $_POST['email']);
$password = mysqli_real_escape_string($link,$_POST['password']);
$query = "SELECT id FROM `users` WHERE email = '".$email."' LIMIT 1";
$result=$link->query($query);
if (mysqli_num_rows($result) > 0) {
$error = "That email address is taken.";
} else {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$query = "INSERT INTO `users`(`email`,`password`) VALUES ('".$email."', '".$hashedPassword."')";
if (!mysqli_query($link,$query)) {
$error = "<p>Could not sign you up, please try again later</p>";
} else {
$_SESSION['id'] = mysqli_insert_id($link);
if(isset($_POST['stayLoggedIn']) and $_POST['stayLoggedIn'] == 1) {
setcookie('id', mysqli_insert_id($link), time()+60*60*24);
}
header("Location: loggedinpage.php");
}
}
} else {
$email = mysqli_real_escape_string($link, $_POST['email']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$hashedPassword = password_hash($password,PASSWORD_DEFAULT);
$query = "SELECT * FROM users WHERE email = '".$email."' LIMIT 1";
$result = $link->query($query);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if ($email == $row['email'] and password_verify($password,$row['password'])) {
if (isset($_POST['stayLoggedIn']) and $_POST['stayLoggedIn'] == 1) {
setcookie('id', $row['id'], time()+60*60*24);
header("Location: loggedinpage.php");
}
} else {
$error = "Incorrect Username/Password combination";
}
}
}
}
}
Although it's tucked away at the end of a paragraph, PHP documentation does say that "it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice)."
The current default algorithm, bcrypt, generates hashes that are 60 characters long. If your database column cannot hold at least this many characters, your hashes will be truncated and verification will fail.
You've got a few other problems as well:
You're modifying the password before generating the hash (with mysqli_real_escape_string())
You're not using prepared statements
You appear to be relying on cookies for authentication. Cookies are user-generated data, they are not to be trusted! This is why PHP provides session support, because the data is stored on the server.
You should not be checking for an existing email address using a query, instead you should have a unique index set on the email column in the database.
try
if(password_verify($password, (string)$row->password)){
//Your Code
}
because of password_verify function return Boolean only true or false
And
$hashedPassword = password_hash($password,PASSWORD_DEFAULT);
Only add once when you Insert to Sql (new user)

How to login to an existing user account with an encrypted (blowfish) password

I followed a tutorial on youtube on how to encrypt users password using the encrypt blowfish function. I have implemented it properly into my registration script, with it successfully registering an account and sending the encrypted password to the database. My issue though, is retrieving that encrypted password when trying to log a user in. When I try and login to an existing user, it gets down to that last else statement saying it doesn't exist, meaning the hashed password isn't being recognized.
Code for encrypt password function:
public function encryptPass($password, $rounds = 11)
{
$salt = "";
// creates array of capital letters A-Z & lowercase as well as #'s 0-9
$saltChars = array_merge(range('A', 'Z'), range('a', 'z'), range(0,9));
for($i = 0; $i < 22; $i++)
{
// randomize the array
$salt .= $saltChars[array_rand($saltChars)];
}
return crypt($password, sprintf('$2y$%02d$', $rounds) . $salt);
}
Code used to register an account:
/// REGISTER ACCOUNT ///
if(isset($_POST['register']))
{
// clean up the fields
$username = mysql_real_escape_string(trim($_POST['username']));
$emailid = mysql_real_escape_string(trim($_POST['emailid']));
$password = mysql_real_escape_string(trim($_POST['password']));
$confirmPassword = mysql_real_escape_string(trim($_POST['confirm_password']));
if($password == $confirmPassword)
{
$iUe = $dbMan->ifUsernameExist($username);
$iEe = $dbMan->ifEmailExist($emailid);
// if username and email don't already exist, continue with registration
if(!$iUe && !$iEe)
{
// encrypt the users password
$hashedPassword = $dbMan->encryptPass($password);
echo "$password <br> \n";
// register the account
$register = $dbMan->UserRegister($username, $emailid, $hashedPassword);
// if registration was succesful
if($register)
{
echo "<script>alert('Registration Successful')</script>";
}
else
{
echo "<script>alert('Registration Not Successful')</script>";
}
}
else
{
echo "<script>alert(' That email or username already exists! ')</script>";
}
}
else
{
echo "<script>alert(' Passwords do not match! ')</script>";
}
}
Code used for the login:
/// LOGIN ACCOUNT ///
if(isset($_POST['login']))
{
// 'convert' post variables to session variables
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
// clean em up, get rid of any white spaces or sql injection special chars
$username = mysql_real_escape_string(trim($_SESSION['username']));
$password = mysql_real_escape_string($dbMan->encryptPass(trim($_SESSION['password'])));
echo "$password<br>\n";
$user = $dbMan->Login($username, $password);
// if theres an acccount with that username/pw in the db
if ($user)
{
// login successful
header("location:index.php");
}
else
{
// Registration Failed
echo "<script>alert(' The email or password do not match! ')</script>";
}
}
Code for dbManager:
<?php
require_once 'dbConnect.php';
//session_start();
class dbManager
{
function __construct()
{
// connecting to database
$db = new dbConnect();
}
// destructor
function __destruct()
{
}
public function UserRegister($username, $emailid, $password)
{
$query = mysql_query("INSERT INTO users(username, emailid, password) values('".$username."','".$emailid."','".$password."')") or die(mysql_error());
return $query;
}
public function Login($username, $password)
{
$query = mysql_query("SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."'");
$user_data = mysql_fetch_array($query);
//print_r($user_data);
$num_rows = mysql_num_rows($query);
if ($num_rows == 1)
{
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['id'];
$_SESSION['username'] = $user_data['username'];
$_SESSION['emailid'] = $user_data['emailid'];
return TRUE;
}
else
{
return FALSE;
}
}
// check if username exists in db
public function ifUsernameExist($username)
{
$qr = mysql_query("SELECT * FROM users WHERE username = '".$username."'");
echo $row = mysql_num_rows($qr);
if($row > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
// check if email exists in db
public function ifEmailExist($emailid)
{
$qr = mysql_query("SELECT * FROM users WHERE emailid = '".$emailid."'");
echo $row = mysql_num_rows($qr);
if($row > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
// encrypt password
public function encryptPass($password, $rounds = 11)
{
$salt = "";
// creates array of capital letters A-Z & lowercase as well as #'s 0-9
$saltChars = array_merge(range('A', 'Z'), range('a', 'z'), range(0,9));
for($i = 0; $i < 22; $i++)
{
// randomize the array
$salt .= $saltChars[array_rand($saltChars)];
}
return crypt($password, sprintf('$2y$%02d$', $rounds) . $salt);
}
}
?>
Note: both the login and register 'methods' are in the same php file including the form markup. The encrypted function is located in a different file called dbManager.
Hopefully I provide enough information for someone to point me in the right direction. Any help is appreciated!
Thanks, Dev.
You need to pass your cleartext password to encrypt to compare it within the database.
change
$password = trim(mysql_real_escape_string($_SESSION['password']));
to
$password = $dbMan->encryptPass(trim(mysql_real_escape_string($_SESSION['password'])));
In your login action.
Ideally you would run the $dbMan->encryptPass before doing mysql_real_escape_string both on INSERTand SELECT.
$password = mysql_real_escape_string($dbMan->encryptPass(trim($_SESSION['password'])));
The salts have to be the same for encrypt and decrypt, seeing as you are using array_rand the salts are different on each pass. You have to store the salt someplace else. If you remove the salt or set it to a constant it will work now.

How can I read an encrypted password from the database to allow users access?

I am unable to match the password returned by the crypt() function to allow users access.
My cryptPassword 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);
}
My registration form:
if($_POST['register']) {
if($_POST['username'] && $_POST['email'] && $_POST['password']) {
$username = mysqli_real_escape_string($dbCon, $_POST['username']);
$email = mysqli_real_escape_string($dbCon, $_POST['email']);
$password = mysqli_real_escape_string($dbCon, cryptPass($_POST['password']));
// insert into databse...
}
}
My login form:
if($_POST['username'] && $_POST['password']) {
$username = mysqli_real_escape_string($dbCon, $_POST['username']);
$inputPassword = mysqli_real_escape_string($dbCon, $_POST['password']);
$password = "SELECT * FROM users WHERE password = '$inputPassword'";
$hashedPass = cryptPass($password);
if(crypt($inputPassword, $hashedPass) == $hashedPass) {
die("<br>Password is a match. Log in");
} else {
echo "<br>Passwords do not match!!! Do NOT log user in <br>";
}
}
I have tested to see why I am unable to log the users in, these are the results:
user name: 2, password: 2 - logging in -> results ->
Passwords do not match!!! Do NOT log user in:
$inputPassword = 2
$query password = SELECT * FROM users WHERE password = '2'
$hashedPass = $2y$09$ICAfpjSJyXEp93JsUbhyieaeMX7KNC6vQSayc0nT6QLHWrMjdYQhi
crypt($inputPassword, $hashedPass) = $2y$09$ICAfpjSJyXEp93JsUbhyie9dqXeWEVqCYGR3faLHveUp1LsJegxpu
As you can see, the first part is identical ($2y$09$ICAfpjSJyXEp93JsUbhyie), however the other part is constantly changing. I believe it has to do with the $salt I'm adding? If so, how can I match the passwords to allow access to my users?
Check out hash_equals. Also, here is an article on the implementation.

Using PHPass to hash password trouble

I am using PHPASS to store password encrypted and compare when login.
here is the code
ob_start();
$userName = $password = "";
$userNameErr = $passwordErr = $loginErr = "";
$hasher = new PasswordHash(8, false);
if (isset($_POST['subEmployee'])) {
if (empty($_POST['user_name'])) {
$userNameErr = "User name is required";
} else {
$userName = check_input($_POST['user_name']);
if (!preg_match("/^[0-9_a-zA-Z]*$/", $userName)) {
$userNameErr = "Only letters, numbers and '_' allowed";
}
}
if (empty($_POST['password'])) {
$passwordErr = "Password is required";
}else{
$password = check_input($_POST['password']);
}
$active = 1;
$loginUser = $db->prepare("SELECT password FROM users WHERE user_name=? AND activity=?");
$loginUser->bind_param('si', $userName, $active);
if ($loginUser->execute()) {
$results = $loginUser->get_result();
if ($results->num_rows == 1) {
$row = $results->fetch_object();
$stored_hash = "*";
$stored_hash = $row->password;
$check = $hasher->CheckPassword($password, $stored_hash);
if ($check) {
$_SESSION['name'] = $row->first_name;
$_SESSION['userId'] = $row->id;
$_SESSION['user'] = 1;
print_r($_SESSION);
header("Location:?pid=4");
} elseif (!empty($_POST['user_name']) && !empty($_POST['password'])) {
$loginErr = "'Invalid Login Information'";
}
}
}
}
so far it always give the same message 'Invalid Login Information' I have made the registration form that store my password like this.
$hasher = new PasswordHash(8, false);
$hash = md5(rand(0, 1000));
if (empty($_POST['password'])) {
$error ['passwordErr'] = "Password is required";
} elseif (strlen($_POST['password']) < 8) {
$error ['passwordErr'] = "<span class='notAllowed'>Chose password with at last eight characters</span>";
} elseif (strlen($_POST['password']) > 72) {
$error ['passwordErr'] = "<span class='notAllowed'>Password max 72 characters</span>";
} elseif ($_POST['password'] !== $_POST['confirm']) {
$error ['passwordErr'] = "Password don't matching";
} else {
$password = $hasher->HashPassword($password);
}
when I checked my database the password seems hashed to me and the user name is there and everything is alright
but still getting this message as 'Invalid Login Information'.
does this two lines is right
$loginUser = $db->prepare("SELECT password FROM users WHERE user_name=? AND activity=?");
$loginUser->bind_param('si', $userName, $active);
does the login code OK.
I try this too
Update
I updated my code
if (isset($_POST['subEmployee'])) {
$error=array();
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
if (empty($_POST['user_name'])) {
$userNameErr = "User name is required";
} else {
$userName = check_input($_POST['user_name']);
if (!preg_match("/^[0-9_a-zA-Z]*$/", $userName)) {
$userNameErr = "Only letters, numbers and '_' allowed";
}
}
if (empty($_POST['password'])) {
$passwordErr = "Password is required";
} else {
$password = $_POST['password'];
}
$active = 1;
$loginUser = $db->prepare("SELECT password FROM hired_person_info WHERE user_name=? AND activity=?");
$loginUser->bind_param('si', $userName, $active);
if ($loginUser->execute()) {
$results = $loginUser->get_result();
if ($results->num_rows == 1) {
$row = $results->fetch_object();
$stored_hash = "*";
$stored_hash = $row->password;
$check = $hasher->CheckPassword($password, $stored_hash);
if ($check) {
$_SESSION['name'] = $row->first_name;
$_SESSION['userId'] = $row->id;
$_SESSION['user'] = 1;
print_r($_SESSION);
header("Location:?pid=4");
} elseif (!empty($_POST['user_name']) && !empty($_POST['password'])) {
$loginErr = "'Invalid Login Information'";
}
} else {
$loginErr = "'We didn't find any users'";
}
}
}
add this from the manual of PHPass
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
still no luck can somebody tell me where am mistaking here
Edit
this is my check_input() code
function check_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
and I am using PHP 5.3.29
Thanks
These are some points i would check:
1) In your registration handler you check directly the POST variable, but for hashing you take a variable $password, i would access the input always in the same way, for example:
$password = $hasher->HashPassword($_POST['password']);
2) The function check_input() is not recommended for passwords, since you calculate a hash-value and this hash-value is "safe" anyway. Even for other user input, one should validate it as you did, but escaping should be done as late as possible, and only for the particular output. So the function htmlspecialchars() should not be called for user input, but always before outputting to HTML.
3) In your login handler you access the password once with the POST variable and once with the variable $password. The variable $password is set only in an if statement, so if the input is empty you fill the error but you continue with an uninitialized $password variable. Either fill the variable just at the beginning, or always use the POST variable.
4) Since you are using PHP 5.3.29 you can use the new function password_hash() with the compatibility pack. I do not think that the PHPass library is the problem here, nevertheless here is an example for the new function.
// 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);
5) Another often made mistake is, that the database field for storing the hash-value is too short, it needs a length of varchar(60). Maybe you could provide one of your password-hashes (of course only an example)?
This library requires PHP >= 5.3.7 OR a version that has the $2y fix backported into it (such as RedHat provides).

Categories