简体   繁体   中英

PHP/MYSQL Authenticate user login using salt password?

I am brand new to MySQL and PHP so apologies, but I'm having problems trying to get my code to work. Users can register on my site with a username and password. I understand that a password should be stored using an encryption method called salt. So having done that now I want the user to be able to login and I'm not sure I'M doing it right.

at the moment I get an error:

Fatal error: Call to undefined function db() in C:\xampp\htdocs\hewden\ssa\suppliers\include\validate_login.php on line 16

here's my registration code:

<?php 
    session_start();
    include("../include/config.php");
    //retrieve our data from POST
    $contactname = $_POST['contactname'];
    $compname = $_POST['compname'];
    $username = $_POST['emailaddress'];
    $password1 = $_POST['password1'];
    $password2 = $_POST['password2'];

    if($password1 != $password2) {
    $_SESSION['message2'] = '<div id="message_box2"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"></div><h23>Ooops!</h23><p>The Password&#39;s did not match.</p> </div>';
    header("location:..\sign-up.php");

    }else{
    if(strlen($username) > 30) {
    $_SESSION['message2'] = '<div id="message_box2"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"></div><h23>Ooops!</h23><p>The Username you have selected is incorrect.</p> </div>';
    header("location:..\sign-up.php");

    }else{

    $hash = hash('sha256', $password1);

    function createSalt(){
    $text = md5(uniqid(rand(), true));
    return substr($text, 0, 3); }
    $salt = createSalt();
    $password = hash('sha256', $salt . $hash);

    $username = mysql_real_escape_string($username);
    $query = "INSERT INTO supplier_pre_sign (contact_name, company_name, supplier_email, password, salt, date) VALUES ('$contactname','$compname','$username', '$password', '$salt', now())";
    mysql_query($query); //You forgot to add this line
    echo $salt;

    } }?>

and this gets stored in my table 'supplier_pre_sign' like so:

ID (AI)   |   contact_name   |     company_name   |   supplier_email    |    password     |    salt

1               Dave                Hewden            hewden@hewden.com     test(hashed)        431

once registrations get approved they are copied into my other table 'supplier_users'

this table is like so:

ID   |   USERNAME             |   PASSWORD       |   SALT  |  ONLINE
1        hewden@hewden.com        test(hashed)       431      Offline

here's my log in code:

<?php
session_start();
include("config.php");
$tbl_name="internal_users";  
$tbl_name2="supplier_users";  
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword']; 
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql = "select * from $tbl_name where username = '$myusername' and password = '$mypassword',
union
select * from $tbl_name2 where username = '$myusername' and password = '$mypassword'";

$sql = db("select * from $tbl_name where username = '$myusername' and password = '$mypassword',
    union
select * from $tbl_name2 where username = '$myusername' and password = '$mypassword'",
    $_POST['myusername'], hmac_hash("sha256", $_POST['mypassword'], $salt));
if(numRows($res) > 0) {


$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row=mysql_fetch_array($result);
if($count==1){
session_start();
$_SESSION['user']=$myusername;
$_SESSION['username']=$row['First_Name'];
if(isset($_SESSION['val']))
$_SESSION['val']=$_SESSION['val']+1;
if($result){
$sql2 = "UPDATE $tbl_name2 SET online = 'online' WHERE online = 'offline'";  
$result2=mysql_query($sql2); }
else
$_SESSION['val']=1;
header("location:../dashboard.php");
}
else {
    echo mysql_error();
$_SESSION['message2'] = '<div id="message_box2"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"></div><h23>Oooops!</h23><p>The Username and Password Combination do not match. Please try again.</p> </div>';
header("location:../index.php");
} }
ob_end_flush();
?>

now my question is how do I get my login script to authenticate the user as I don't really understand how the salt works, my user would just type in 'test' expecting it to log them in, so how do I log them in by checking the salt password matches?

Thanks in advance

PHP has now a built in function password_hash() for this purpose. The function generates a BCrypt hash of length 60 characters (including the salt), so you don't have to store the salt separately.

// 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);

PS Do not use any hash algorithms like SHA-* or MD5 because they do not have a cost factor and are ways too fast. For further information you can have a look at my tutorial about safely storing passwords.

You're correct in that using salt is a good idea but you appear to have misunderstood how to use it. Salt is not a separate password but rather extra data added to the password when hashing it so that it makes cracking harder should your database be compromised.

Reading a good tutorial like Secure Salted Password Hashing - How to do it Properly will help you understand the idea better.

So when you hash the password what you should be doing is the following:

$hash = hash('sha256', $password1.$salt);

NB - Not a PHP programmer so syntax errors are me

As for logging in a user you need to first look up the salt from the database based on the username and then hash the provided password with the salt before checking the hash against your database.

Note that it is almost always much better to use a pre-built library such as PHPass for password hashing rather than doing your own implementation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM