0

I'm trying to broaden my knowledge of SQL and PHP, so I'm trying to figure out how to create hashed database entries for user credentials on a project I'm working on. Right now in the planning stage, I'm storing everything into session cookies, but in the final product I would like to have everything stored on my server. I've got a little bit of documentation on salting/hashing strings, but I'm not sure how to store and then check if the stored hash is proper.

<?php
    $username = $_GET["$us"];
    $password = $_GET["$pa"];
    $expire = time()+60*60*24*14; //Cookies expire in two weeks
    setcookie("username", $username, $expire);
    setcookie("password", $password, $expire);
?>

Right now I have a login-page posting $us and $pa to a login-submit.php page with the above code. If I hash it using md5 or similar, how would I store it in my database and when pulled up from the login page, check if the password is correct? I was thinking of:

<?php
    $userhash = md5($us);
    $passhash = md5($pa);
    $rows = $db->query("
        INSERT INTO credentials
        VALUES ($passhash, $userhash);"
    );
?>

Is this at all right? As an aside, how would I check if a user exists on the database, and if so, reverse the md5 hash back to plaintext so I can work with it?

gator
  • 3,465
  • 8
  • 36
  • 76
  • 1
    You can't reverse a hash, by design (although lookup tables are available on the internet to reverse trivial passwords, so you should also use salting, as Andrew says). To check a password when logging on, perform the same hashing on the input, and compare the result to the hashed password in the database. – halfer Jan 01 '13 at 20:31

4 Answers4

2
  1. Don't use cookies. Use sessions. (sessions store things on the server automatically and just use a cookie to retrieve it).

  2. Secondly MD5 isn't secure for passwords. It has collisions and it's vulnerable to brute-force attacks. See the first answer to this question: How can I store my users' passwords safely?

Community
  • 1
  • 1
Cfreak
  • 19,191
  • 6
  • 49
  • 60
2

Instead of using cookies, use sessions, they store the data serversided. For password encryption use the very safe blowfish algorithm using crypt().

Nox
  • 339
  • 1
  • 9
2

This is probably the best Script I have found to hash passwords. All good user sites should start with the login script first, not later.

Hashing a password

I used this to create a class to prepare the password for database insertion and it works great.

Here is the class:

    <?php
/**
* User Login Class
*
* LICENSE:      (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2)
*
* COPYRIGHT:    Finley Designs
* CONTACT:      ffrinfo@yahoo.com
* DESIGNED BY:  Roy Finley
* VERSION:  1.0
* Password hashing with PBKDF2.
* This class uses the pdkdf2 functions designed by : havoc AT defuse.ca : www: https://defuse.ca/php-pbkdf2.htm
* 
*/
class PasswordProcessor
{
//CREATE HASH FROM USER PASSWORD FOR NEW USER OR LOST PASSWORD
public function create_hash($password)
{
    // format: algorithm:iterations:salt:hash
    $salt = base64_encode(mcrypt_create_iv(24, MCRYPT_DEV_URANDOM));
    return  "sha256:1000:" .  $salt . ":" . 
        base64_encode($this->pbkdf2(
            "sha256",
            $password,
            $salt,
            1000,
            24,
            true
        ));
}
//VALIDATE USER PASSWORD
public function validate_password($password, $good_hash)
{
    $params = explode(":", $good_hash);
    if(count($params) < 4)
       return false; 
    $pbkdf2 = base64_decode($params[3]);
    return $this->slow_equals(
        $pbkdf2,
        $this->pbkdf2(
            $params[0],
            $password,
            $params[2],
            (int)$params[1],
            strlen($pbkdf2),
            true
        )
    );
}

// COMPARE TWO STRINGS IN LENGTH-CONSTANT TIME.
private function slow_equals($a, $b)
{
    $diff = strlen($a) ^ strlen($b);
    for($i = 0; $i < strlen($a) && $i < strlen($b); $i++)
    {
        $diff |= ord($a[$i]) ^ ord($b[$i]);
    }
    return $diff === 0; 
}
//HASHING ALGORITHM
private function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false)
{
    $algorithm = strtolower($algorithm);
    if(!in_array($algorithm, hash_algos(), true))
        die('PBKDF2 ERROR: Invalid hash algorithm.');
    if($count <= 0 || $key_length <= 0)
        die('PBKDF2 ERROR: Invalid parameters.');

    $hash_length = strlen(hash($algorithm, "", true));
    $block_count = ceil($key_length / $hash_length);

    $output = "";
    for($i = 1; $i <= $block_count; $i++) {
        // $i encoded as 4 bytes, big endian.
        $last = $salt . pack("N", $i);
        // first iteration
        $last = $xorsum = hash_hmac($algorithm, $last, $password, true);
        // perform the other $count - 1 iterations
        for ($j = 1; $j < $count; $j++) {
            $xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
        }
        $output .= $xorsum;
    }

    if($raw_output)
        return substr($output, 0, $key_length);
    else
        return bin2hex(substr($output, 0, $key_length));
}
}//CLOSE PasswordProcessor CLASS
?>

Remember this is a very small part of authenticating your users..... Search google and read, read , read Other points to Make

  • Your Database needs two user - One that can read only for login and one that can read and write for the registration script.

  • Use Captcha on the register form

  • never tell the user what part of login failed, just that it did.

ROY Finley
  • 1,406
  • 1
  • 9
  • 18
1

Compare the hash of the entered (password+salt) to the stored hash of the (password+salt). You will need to also store the salt in the database.

Edit: there's no need to hash the username. You wouldn't be able to extract it from the hash. You could, however, encrypt it.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84