PHP reset Password - php

I am confused about how to encrypt the new password to go in the database. When I enter the password it will encrypt and check the database correct and to verify for the new password it will just change it to plain text.
if (count($_POST) > 0) {
$result = mysqli_query($conn, "SELECT *from users WHERE id='" . $_SESSION["id"] . "'");
$row = mysqli_fetch_array($result);
if (MD5(mysqli_real_escape_string($_POST["currentPassword"] == $row["password"]))) {
mysqli_query($conn, "UPDATE users set password='" . $_POST["newPassword"] . "' WHERE id='" . $_SESSION["id"] . "'");
$message = "Password Changed";
} else
$message = "Current Password is not correct";
}

// password encryption for security.
$salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$salt = base64_encode($salt);
$salt = str_replace('+', '.', $salt);
$hash = crypt($pass, '$2y$10$'.$salt.'$');
//echo ("".$hash."<br />\n");
$pass is the password from the password input
save $hash to the database
verify the password with that got from the database $hash
if(password_verify($pass, $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
update and try that procedure

for simple application you can use base64_encode() to encrypt and store it into database when new password is entered. and for login also encrypt the entered password and match it with database.
your code:
if (count($_POST) > 0)
{
$result = mysqli_query($conn, "SELECT *from users WHERE id='" . $_SESSION["id"] . "'");
$row = mysqli_fetch_array($result);
$entered_password = base64_encode($_POST["currentPassword"]);
$new_password = base64_encode($_POST["newPassword"]);
$id = $_SESSION["id"] ;
if ($entered_password == $row["password"]))) {
$result = mysqli_query($conn, "UPDATE users set password='" . $new_password . "' WHERE id='" .$id. "'");
$message = "Password Changed";
} else
$message = "Current Password is not correct";
}
its a simply way.

//password encryption
$user_password = "1234";
$hash_pass = password_encryption($user_password, PASSWORD_BCRYPT, array('cost'=>10);
//"$user_password"-password obtained from the user input
//"$hash_pass" -encrypted password stored in a database
//verify the user password with that obtained from the database
if(password_verify($user_password, $hash_pass)){
echo "password is valid";
}else{
echo "password is not valid";
}
try this out.

Related

How to check login in PHP?

i have problem with login , when i entered correct username and wrong password the result should not allow me to login but in my case if the username correct and the password wrong it's allow me to login to the application.
here is my login script
<?PHP
include_once("conn.php");
$user= $_POST['userName'];
$password = mysqli_real_escape_string($_POST['password']);
$qr="select password from user where userName='$user'";
$res=mysqli_query($con, $qr);
while($row=mysqli_fetch_array($res)){
$pass=$row[0];
}
$saltQuery = "select salt from user where userName = '$user'";
$result = mysqli_query($con , $saltQuery);
while($row=mysqli_fetch_array($result)){
$salt = $row[0];
}
$saltedPW = $password . $salt;
$hashedPW = hash('md5', $saltedPW);
if($pass==$hashedPW){
$query = "SELECT userName, password FROM user WHERE userName = '$user' AND password = '$hashedPW'";
$result = mysqli_query($con, $query);
if($result->num_rows > 0){
echo"success login ";
} else{
echo"failed login ";
}
Try to do something that for login page.
<?php
include("config.php");
if(isset($_POST['submit']))
{
echo $username= $_POST['username'];
echo $password= $_POST['password'];
$username = addslashes($username);
$password = addslashes($password);
$username = mysqli_real_escape_string($link, $username);
$password = mysqli_real_escape_string($link, $password);
$pass= md5($password);
$seladmin ="SELECT id,UserName,Password FROM login WHERE UserName='$username' && Password='$pass'";
$SelRecAdmin = mysqli_query( $link,$seladmin );
$row = mysqli_fetch_array($SelRecAdmin);
$tot_num_row=mysqli_num_rows($SelRecAdmin);
if($tot_num_row >0)
{
$_SESSION['adminid']=$row['id'];
$_SESSION['adminunm'] = $row['UserName'];
header('location:home.php');
exit;
}
else
{
$_SESSION['msg']= 'Invalid username or password';
header('location:index.php');
exit;
}
}
?>
I have developed a solution for your question. I didn't run it, if you get any syntax errors kindly fix it by yourself.
**Make sure you don't have same Username in your code, Otherwise it'll show success message if if you enter wrong password. (As per your code ).
But the following code should give you the expected results even if you have multiple entries with same username. **
<?PHP
include_once("conn.php");
$user= $_POST['userName'];
$password = mysqli_real_escape_string($_POST['password']);
$password = hashIt($password,$user);
$res=mysqli_query($con,"select * from user where userName='".$user."' AND password='".$password."'");
if(mysqli_num_rows($res) == 1){
echo "Login Successfull";
}else{
echo "Invalid Username/Password";
}
function hashIt($password,$user){
$result = mysqli_query($con,"select salt from user where userName = '".$user."'");
// No need to check other things, if query fails / no records found anyway it'll show login failure message.
while($row=mysqli_fetch_array($result)){
$salt = $row['salt'];
}
$saltedPW = $password . $salt;
return hash('md5', $saltedPW);
}
?>

How to take and verify hashed password from db [duplicate]

This question already has answers here:
Password is not verified using function password_verify
(4 answers)
Closed 6 years ago.
In my register.php i use this code to make hashed password:
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
And i want to verify password hash in db but i dont know how to use password_verify correctly. Here is my login.php script to login
login.php
<?php
include('Global/global.inc.php');
if(isset($_SESSION['user_name'])!='') {
header("Location: index.php");
}
include('Global/view/view.login.php');
//check if form is submitted
if (isset($_POST['signin'])) {
$user_name = mysqli_real_escape_string($connect, htmlspecialchars($_POST['user_name']));
$user_pass = mysqli_real_escape_string($connect, htmlspecialchars($_POST['user_pass']));
$result = mysqli_query($connect, "SELECT * FROM `" . USERS_TABLE . "` WHERE user_name = '$user_name' AND user_pass = '$user_pass'");
if (empty($user_name) || empty($user_pass)) {
echo "empty fields";
}
if ($row = mysqli_fetch_array($result)) {
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_avatar'] = $row['user_avatar'];
$_SESSION['user_mail'] = $row['user_mail'];
header("Location: index.php");
}
else {
echo 'Invalid Username or Password!<br />';
}
}
from the manual http://php.net/manual/en/function.isset.php
isset — Determine if a variable is set and is not NULL
isset() returns bool true or false you should only have
if (isset($_SESSION['username']))
use password_verify();
http://php.net/manual/en/function.password-verify.php
example
<?php
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify($password, $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
i edited your code and added some comments to make it clear hope it helps
if( isset($_SESSION['user_name']) ) {
header("Location: index.php");
}
include('Global/view/view.login.php');
//check if form is submitted
if (isset($_POST['signin'])) {
$user_name = mysqli_real_escape_string($connect, htmlspecialchars(trim($_POST['user_name'])));
$user_pass = trim($_POST['password']); // trim deletes spaces from left and right password doesn't need sanitization
//check fields
if (empty($user_pass) || empty ($user_name) ) {
echo "empty fields";
}
elseif ($result = mysqli_query($connect,$sql)){
// check username if it exists procceds to password checking
if (mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$hashedpassword = $row["password"];
//check password if username exists
if (password_verify($password, $hashedpassword))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_avatar'] = $row['user_avatar'];
$_SESSION['user_mail'] = $row['user_mail'];
header("Location: index.php");
}
} else {
echo 'Invalid Username or Password!<br />';
} } else {
echo 'Invalid Username or Password!<br />';
}
}
If you want to check the login password with the DB hashed password, then convert the login password to hash and compare them both. That is:
$user_pass = password_hash($user_pass, PASSWORD_DEFAULT);
$result = mysqli_query($connect, "SELECT * FROM `" . USERS_TABLE . "` WHERE user_name = '$user_name' AND user_pass = '$user_pass'");
if (empty($user_name) || empty($user_pass)) {
echo "empty fields";
}
if ($row = mysqli_fetch_array($result)) {
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_avatar'] = $row['user_avatar'];
$_SESSION['user_mail'] = $row['user_mail'];
header("Location: index.php");
}
else {
echo 'Invalid Username or Password!<br />';
}
}

php code not working, $query string not working well

formatted code:
<?php
require_once 'connectvars.php';
if (isset($_POST['submit'])) {
//set vars
$oldpw = mysqli_real_escape_string($dbc, trim($_POST['oldpw']));
$newpw = mysqli_real_escape_string($dbc, trim($_POST['newpw']));
$retype = mysqli_real_escape_string($dbc, trim($_POST['retype']));
$query = mysqli_query($dbc, 'SELECT password from user_info WHERE password = "hash(\'SHA256\',$oldpw)" and user_id = "$SESSION[\'user_id\']"'); // this line is "not working well"
if (strlen($newpw) < 7) {
if (strlen($newpw) > 32 ) {
if (mysqli_num_row($query) == 1) {
if ($newpw == $retype) {
mysqli_query($dbc, "UPDATE user_info SET password = 'hash('SHA256',$newpw)'");
$msg = "You successfully changed your password";
}
else {
$msg = "Your old password doesn't match.";
}
}
else {
$msg = "You must enter your old password correct.";
}
}
else {
$msg = "Your password must contain 32 characters or less.";
}
}
else {
$msg = "Your new password must contain at least 7 characters.";
}
?>
I think you want to improve your sql syntax.
'SELECT password
from user_info
WHERE password = "hash(\'SHA256\',$oldpw)"
and user_id = "$SESSION[\'user_id\']"'
may be corrected to
"SELECT password
from user_info
WHERE password = '" . hash('SHA256',$oldpw) ."'
and user_id = '" . $_SESSION['user_id'] . "'"
to propperly escape the string. Try to correct your update statement the same way.

PHP login system with encryption (doesn't log in)

I'm struggling with an aspect of something I am trying to do. I am trying to create a basic password management system but I cannot login with an encrypted password. The password does get encrypted on the DB after using the account management page, but when I log out and try to log back in it no longer works.
Here is my code for the login page and change password page: I am aware that SQL injection is a problem but I haven't got round to sorting that part out yet.
LOGIN2.PHP
<link rel="stylesheet" type="text/css" href="default.css" media="screen"/>
<?php
session_start();
$dbname = "obsidian";
if(isset($_POST['sub'])){
//encryption for salt---------------------------------
function makeSalt($salt_length)
{ // only these characters are allowed in salt strings
$saltset = './0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// note that this method only allows up to 6 duplicate chars
$saltchar = "$saltset$saltset$saltset$saltset$saltset$saltset";
// shuffles string randomly & grabs 1st n for our salt
$salt = substr(str_shuffle($saltchar), 0, $salt_length);
return $salt;
}
//Login Script
$username = $_POST['username'] ;
$password = $_POST['password'] ;
//ENCRYPTS THE USER ENTERED PASSWORD
$salt = '$5$rounds=1000$' . makeSalt(16) . '$';
$hashed_password = crypt($password, $salt);
//CONNECT TO DB
$mysqli = new mysqli('localhost','admin1', 'password1','obsidian' ) or die('Failed to connect to DB' . $mysqli->error );
$sSQL = "select * from users where password='$hashed_password' AND username='$username'";
$result = mysqli_query( $mysqli, $sSQL);
if (!$sSQL) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$row = mysqli_fetch_array($result);
if(!$row){
echo "<div>";
echo "No existing user or wrong password.";
echo "</div>";
session_destroy();
header("Location: index.php");
}
else {
$_SESSION['userid'] =$username;
header("Location: index.php");
}
}
?>
And this is the PHP script for the changing of passwords.
<?php
session_start();
$dbname = "obsidian";
if(isset($_POST['change'])){
//CREATE SALT-------------------------------------------------------------------------
function makeSalt($salt_length)
{ // only these characters are allowed in salt strings
$saltset = './0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// note that this method only allows up to 6 duplicate chars
$saltchar = "$saltset$saltset$saltset$saltset$saltset$saltset";
// shuffles string randomly & grabs 1st n for our salt
$salt = substr(str_shuffle($saltchar), 0, $salt_length);
return $salt;
}
//Entered credentials from form---------------------------------------------------------
$oldPass = $_POST['oldPass'];
$newPass = $_POST['newPass'];
$newPassAgain = $_POST['newPassAgain'];
//Connect to DB-------------------------------------------------------------------------------
$mysqli = new mysqli('localhost','admin1', 'password1','obsidian' ) or die('Failed to connect to DB' . $mysqli->error );
//CHECK IF OLD PASS AND SESSION ID EQUAL-----------------------------------------------------
$sSQL = ("select * from users WHERE password='$oldPass' AND username= '" . $_SESSION["userid"] . "'");
$result = mysqli_query( $mysqli, $sSQL);
if (!$sSQL)
{
printf("Error: %s\n", mysqli_error($con));
exit();
}
$row = mysqli_fetch_array($result);
//IF THERE ARE NO ROWS, DO NOT CHANGE PASSWORD-------------------------------------------
if(!$row)
{
echo "<div>";
echo "No existing user or wrong password.";
header("Location: account.php");
echo "</div>";
session_destroy();
}
//IF THERE ARE ROWS ENCRYPT AND CHANGE PASSWORD----------------------------------------
else {
$salt = '$5$rounds=1000$' . makeSalt(16) . '$';
$hashed_password = crypt($password, $salt);
if ($newPass == $newPassAgain){
$update = ("UPDATE users SET password = '$hashed_password' where username= '" . $_SESSION["userid"] . "'") or die (mysql_error());
if ($mysqli->query($update) === TRUE) {
echo "Record updated successfully";
header("Location: success.php");
}
else {
echo "Error updating record: " . $mysqli->error;
}
}
}
}
A point in the right direction would be appreciated.
Thanks
You are hashing a password with a random salt each time.
Example code:
echo makeSalt(16) . "\n";
echo makeSalt(16) . "\n";
echo makeSalt(16) . "\n";
Outputs:
oAv0cGIzTECgF1gI
ypZegnQoS.d/inqA
6PPXZ/.YfupGuxPg
In order for the hash to be the same, the salt has to be the same. Though having the same salt for every user is not as secure as having a different hash for every user.
You could for example consider making the salt based on the username, or store the salt and the hash and then select the salt and encrypted password from the database for the user who is attempting to login.
Then the hash should match if you hash the supplied password with the same salt.
Furthermore, consider using sha_512 instead of sha__256. ($5$ -> $6$).
Also consider using mysqli or PDO as you will have more secure queries (Less chance on mysql injections).
(Pseudoish code)
(Insert code)
$salt = '$6$rounds=1000$' . makeSalt(16) . '$';
$hashed_password = crypt($password,$salt);
insert into table (password_salt,password_hash...) values($salt,$hashed_password,.....);
(Verify code)
select password_salt, password_hash.... from table where user = username
if(hash_equals(crypt($password,$password_salt),$password_hash)){
//OK
}else{
//Wrong password!
}
Your encryption system is safe and secure just as this
$user_input = "someone";
$pass_input = "something";
$auth_credentials = hash("sha512", md5(sha1(md5($user_input . $pass_input))));
echo $auth_credentials;
test and feedback.

Phpass - how to check login username and password against username and password hash in database

I have successfully used Phpass to hash registered users passwords and store them in a database, now i am stuck on the login how to check the sumbitted username and password, checking the username exists in the database then checking the hashed password against the one given.
Any help much appreciated!!! Thankyou!
This is my code:
<?php
// Inialize session
session_start();
// Include database connection settings
include('config.inc');
require("PasswordHash.php");
$hasher = new PasswordHash(8, false);
$username = $_POST['username'];
$password = $_POST['password'];
// Passwords should never be longer than 72 characters to prevent DoS attacks
if (strlen($password) > 72) { die("Password must be 72 characters or less"); }
$query = "SELECT * FROM user WHERE username = '$username'";
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows = 1) {
$res = mysql_query("SELECT password FROM user WHERE username = '$username'");
$row = mysql_fetch_array($res);
$hash = $row['password'];
$password = $_POST['password'];
if ($hasher->CheckPassword($password, $hash)) { //$hash is the hash retrieved from the DB
$what = 'Authentication succeeded';
} else {
$what = 'Authentication failed';
}
} else {
echo "No Such User";
include 'login.php';
exit();
}
echo "$what\n";
echo "<br />";
echo "$hash";
?>
THIS IS MY WORKING CODE FOR BENEFIT OF OTHERS:
<?php
// Inialize session
session_start();
// Include database connection settings
include('config.inc');
require("PasswordHash.php");
$hasher = new PasswordHash(8, false);
$username = $_POST['username'];
$password = $_POST['password'];
// Passwords should never be longer than 72 characters to prevent DoS attacks
if (strlen($password) > 72) { die("Password must be 72 characters or less"); }
$query = "SELECT * FROM user WHERE username = '$username'";
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows = 1) {
$res = mysql_query("SELECT * FROM user WHERE username = '$username'");
$row = mysql_fetch_array($res);
$hash = $row['password'];
$password = $_POST['password'];
if ($hasher->CheckPassword($password, $hash)) { //$hash is the hash retrieved from the DB
$what = 'Authentication succeeded';
} else {
$what = 'Authentication failed';
}
} else {
echo "No Such User";
include 'login.php';
exit();
}
echo "$what\n";
echo "<br />";
echo "$hash";
?>
Here's how phpass works: When you save the user's password (when they create it) you hash it before saving, like so:
$hash_iterations = 30;
$portable_hashes = FALSE;
$hasher = new PasswordHash($hash_iterations, $portable_hashes);
$hash_value = $hasher->HashPassword($actual_password);
Then save $hash_value in the database as the user's password. When you go to validate the user, look up the user by username. If found, compare the actual password from the database (stored hash) with a hash of what the user entered:
// $stored_hash is the value you saved in the database for this user's password
// $user_input is the POST data from the user with the actual password
$valid_password = $hasher->CheckPassword($user_input, $stored_hash);
Make sure to initialize the PasswordHash class the same way each time, with the same values for $hash_iterations and $portable_hashes, or the comparison won't work correctly.

Categories