PHP password_verify always returning false even when hardcoded

dean2cool4u

Here's my code:

function login() {
    //Declare variables
    $username = $_POST["login"]; 
    $password = $_POST["password"];
    $client = $_POST["clients"];

    //QueryDB
    $servername = "localhost";
    $SQLUsername = "XXXX";
    $SQLPassword = "XXXX";
    $dbname = "XXXX";

    $conn = new mysqli($servername, $SQLUsername, $SQLPassword, $dbname);
    // Check connection
    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }

    //Set query then run it
    $sql = "SELECT * FROM Users WHERE Username ='$username'";
    $result = $conn->query($sql);
    $row = $result->fetch_array(MYSQLI_ASSOC);

    //Verify Password
     if ($result->num_rows === 1) {
        if (password_verify($password, $row['Password'])) {
            //Build XML request
            $XMLRequest = "<?xml version='1.0'?><Login><Client>".$client."</Client><LoginDetails><Username>".$username."</Username><Password>".$newhash."</Password></LoginDetails></Login>";

            //Build URL
            $ReplacedValues = array("NewType" => "login", "NewHash" => $XMLRequest);
            $NewString = strtr($GLOBALS["params"], $ReplacedValues);

            $NewUrl = $GLOBALS["link"].$NewString;

            //Post to Server
            header('Location: '.$NewUrl);
        }
        else {
            echo "Password is wrong"."<br>";
            echo $password."<br>";
            echo $row['Password'];
        }
    } else {
        echo "more then 1 row";
    }

    mysqli_close($conn);
}

My issue is that even if I hard code my password variable and Hash variable to their respective values the if condition returns false. Any idea why? The page does when it loads, loads the else condition to show me the user input password and the correct hash value from the DB. My DB is set to CHAR(255) for the password.

UPDATE** Here is my C# discussed in the comments. This is not the complete code just up to the part of the insert statement for the DB. I am able to insert into the SQL server DB just fine.

public static string WebsiteRegister(XmlDocument XMLBody)
        {
            //Get SQL connection string
            XmlNodeList XMLNodes = SQLConnectionMethods.EstablishSQLServerConnection("SQL");
            string ConnectionString = XMLNodes.Item(0).ChildNodes[0].InnerText;
            string UserName = XMLNodes.Item(0).ChildNodes[1].InnerText;
            string Password = XMLNodes.Item(0).ChildNodes[2].InnerText;

            //Open connnection
            SqlConnection cnn = new SqlConnection(ConnectionString);
            SQLConnectionMethods.OpenSQLServerConnection(cnn);

            try
            {
                string username = XMLBody.SelectSingleNode("register/registerdetails/username").InnerText;
                string pass = XMLBody.SelectSingleNode("register/registerdetails/password").InnerText;
                string fname = XMLBody.SelectSingleNode("register/registerdetails/firstname").InnerText;
                string lname = XMLBody.SelectSingleNode("register/registerdetails/lastname").InnerText;
                string email = XMLBody.SelectSingleNode("register/registerdetails/email").InnerText;
                string accountRef = XMLBody.SelectSingleNode("register/registerdetails/accountreference").InnerText;
                string client = XMLBody.SelectSingleNode("register/client").InnerText;

                //Build Query string
                string queryString = $"Insert into [dbo].[UserAccounts] (AccountReference, FirstName, LastName, Email, Username, Pass, Client) values ('{accountRef}', '{fname}', '{lname}', '{email}', '{username}', '{pass}', '{client}')";

                //Process request
                using (SqlCommand myCommand = new SqlCommand(queryString, cnn))
                {
                    string Result = (string)myCommand.ExecuteScalar();
Prakhar Gyawali

I could not find any problem in your code here but since hashing and verifying is a process which depends on a lot of factors to be successful i would like to give you some tips so that you can check it yourself for any potential problems.

  1. make sure you are not escaping/sanityzing the password before hashing it. This way you're altering the stored password. Let

    $password = $_POST['password'];

both when you create the account and when you check if the password match at login.

  1. make sure you are enclosing the hash variable in single quotes (') and not double quotes (").using double quotes makes PHP read each paired character with "$" as indivisual variables which will probably cause your code to break, USE SINGLE QUOTES INSTEAD.

  2. Ensure the Password field in the database (that stores the hashed password) is able to store up to 255 characters. From the documentation it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice). If the field is narrower the hash will be truncated and you'll never have a match.

  3. As you get the user by username at login ensure that username is unique as long as it is your primary key (in the table definition). Good idea to check this also upon user registration and login (at php level).

  4. echo both hash and entered values and make sure they match the ones that were inserted and generated during password_hash() if the database value was different (the hash), make sure the type of its column is varchar(256), the hash is usually 60 characters long but the hashing function is frequently improved so that length may expand in the future.

  5. if the entered value was different (the user password), make sure the filtering isn't corrupting the password value.

  6. also check if another variable has the same name as the one you're storing the password in.

  7. If password_verify($password, password_hash($password, PASSWORD_DEFAULT)) "works", then the problem is that $row['Password'] does not contain what is expected - including not being generated correctly.

  8. If it "doesn't work" then another line is causing the observed behavior. Both of these outcomes allow focusing on a refined problem set.

  9. try changing the password from the another column that matched and copy it to your password column and enter that password to check.if it worked then there is problem with your stored password

  10. try copying this hash to your password column

    $2y$10$uDnEpQpkh9RO5tWwOrHtneLAuYMRDstRaKGZFyHubObDR0789OMO6

this is the hashed password for 123456 using bycrypt. select this password and try to verify it with password_verify(123456,$yourhashedfromdatabase) after selecting this from sql if it works then there is probably some manipulation after your data is entered and goes to the database. it it does not then check if the password that reaches the database is exactly as your typed by echoing it.

UPDATE: after you updated your code i see that while entering the password you use "Pass" column but while extracting you use "Password" column. this could be the issue

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related