Understanding how user usernames and passwords are saved, retrieved and verified on websites

Environment: Lets consider you have a web site that is developed in PHP with MySQL DB in the backend and pages being served via the Apache Web Server.  All are freeware technologies with appropriate licensing terms.

 

End User input to Webpage and Webpage to Php script:

A user login and/or registration page will prompt user for providing the username and password to access the site content.  The Login page form, will pass the user provided username and password to the appropriate php script.

 

Php Script to/from DB and back to Web page form:

The php script will

  • make a connection to backend MySQL DB, by using PDO objects.                            $con = new PDO( MYSQL_DSN, MYSQL_USERNAME, MYSQL_PASSWORD );

  • Reads the user provided username and password data     if( isset( $input[‘username’] ) ) $this->username = stripslashes(strip_tags( $input[‘username’] ) );
        if( isset( $input[‘password’] ) ) $this->password = stripslashes( strip_tags( $input[‘password’] ) );

  • Encrypts password by using an Hashing algorithm involving 256/512 bits.             $salt = "RZYbN3X1kkIOGEe8AnX6glShpTrMg";                                                                         $stmt->bindValue( "password", hash("sha512", $this->password . $this->salt), PDO::PARAM_STR );

  • Saves the encrypted password into the MySQL DB using INSERT command                $sql = "INSERT INTO Myusers(username, password) VALUES(:username, :password)";

    $stmt = $con->prepare( $sql );
    $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
    $stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
    $stmt->execute();

  • Retrieve the saved password and verify/validate for the given user from the Database into a variable, if there are results matching the specified user and hashed password combination that indicates the user provided password matches for the username and is given access

    $sql = "SELECT * FROM Myusers WHERE username = :username AND password = :password LIMIT 1";

        $stmt = $con->prepare( $sql );
        $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
        $stmt->bindValue( "password", hash("sha512", $this->password . $this->salt), PDO::PARAM_STR );
        $stmt->execute();

  • Verifying Password for given user:
    • The key would that username has to be unique and can register only once
    • For a given username, there will be only one password (which may or may be unique)
    • However, when you make a combination of username and hashed password, it should result in a unique entry
    • Thus when you are able to fetch a unique result for a given username and password from the MySQL DB, that indicates the user entered a correct username and password. 

Leave a Reply

Your email address will not be published. Required fields are marked *