finec
finec

Reputation: 25

PHP - Comparing hash with database is not working

Notes:

Anyways here is the code:

<?php
session_start();
require("config.php");

if(isset($_POST['submit'])) {

    $username = mysql_real_escape_string($_POST['username']);
    $password = sha1(mysql_real_escape_string($_POST['password']));

    $loginsql = "SELECT * FROM login WHERE username = '" . $username .
    "' AND password = '" . $password . "'";
    $loginresult = mysql_query($loginsql);
    $loginnumrows = mysql_num_rows($loginresult);

    if($loginnumrows == 1) {
        $loginrow = mysql_fetch_assoc($loginresult);
        session_register("USERNAME");
        session_register("USERID");

        $_SESSION['USERNAME'] = $loginrow['username'];
        $_SESSION['USERID'] = $loginrow['id'];

        header("Location: " . $config_basedir . "controlpanel.php");
    }
    else{
        echo "<p>Incorrect Login, please try again!</p>";
    }
}
else{

}
?>

I'm really not too sure where to go with this. I'm sure my code could be more efficient but as I mentioned in the notes, it does work when I don't hash the password. Thank you for reading.

Upvotes: 0

Views: 1981

Answers (4)

krizzo
krizzo

Reputation: 1883

The escaped password is not the same hash as the entered password. The has will not contain any special characters.

abc' sha1 != escaped abc\' sha1

Upvotes: 0

jeroen
jeroen

Reputation: 91792

It seems your passwords in the database are not hashed, you need to change that and your sign-up form so that all use the same hash method.

You can change all passwords in the database using MySQLs SHA1() function.

Upvotes: 1

iblue
iblue

Reputation: 30434

This will not work, if your password contains any ' or other escapeable characters.

$password = sha1(mysql_real_escape_string($_POST['password']));

You should hash first, then escape:

$password = mysql_real_escape_string(sha1($_POST['password']));

And as a SHA1 only contains [a-f0-9], you can as well skip the escpaing

$password = sha1($_POST['password']);

Upvotes: 4

Francis Lewis
Francis Lewis

Reputation: 8980

If it works when you don't hash the password, it sounds like your passwords are stored in the database as plaintext - that would be where I would check.

The other thing that might be happening is mysql_real_escape string should be used on the other side of the sha1 so it doesn't interfere with the exact input.

So it should be: mysql_real_escape_string(sha1($_POST['password'])); That might change things a bit.

Note: Although sha1 doesn't currently have any known security issues so it should be safe to put directly into the database without the mysql escape, somebody once told me to always make sure everything that goes into the database should be cast or escaped just in case a security vulnerability is found in something like sha1 or md5.

Upvotes: 1

Related Questions