0

This is my code to hash

class hashing {
  private static $algo='$2a';
  private static $cost='$10';

  public static function unique_salt() {
	return substr(sha1(mt_rand()),0,22);
  }

 function hash($password) {			
	return crypt($password,self::$algo.self::$cost.'$'.self::unique_salt());
 }

 public static function check_password($hash,$password) {
	$full_salt=substr($hash,0,29);
	$new_hash=crypt($password,$full_salt);
	return ($hash==$new_hash);
 }  
}

This is my login page

require("hashing.php");
$password=hashing::hash($_POST['txtPassword']);
$checkPassword=mysql_query("SELECT * from $tbl_name WHERE Password='".$password."'"); 
$resultPassword=mysql_fetch_row($checkPassword);

if(hashing::check_password($resultPassword['Password'],$_POST['txtPassword'])) {
  echo "login success!";
}
else {
 echo "login failed!";
}

When the user inputs correct password, it is failing to login. How do I solve this problem?

3
Contributors
4
Replies
7
Views
6 Years
Discussion Span
Last Post by diafol
0

When you use hashing::hash() you're going to output a new unique_salt() each time, so when the user registers to the website, this value has to be saved to the database, if you don't store it then your script won't be able to get the right match.

0

The value is saved into the database. Registration page works fine. But login has a problem

1

Run this function, is part of your code:

<?php
function unique_salt() {
	return substr(sha1(mt_rand()),0,22);
  }
echo unique_salt() . "<br />";
echo unique_salt() . "<br />";
?>

You will get something like this:

32f2b4c6e1c81629fa6c02
fdbfe19bbbec167eb4c040

This are salt values, and if you refresh you will get more different values. If you store only the password hash on the database then you can't get the right match, you need to store also the salt.

So, for example, if the hash stored is:

$2a$10$ea04e8df85241ceb9157auxKBW3YKOyHa6XDAZkindtKLZ/GiUcdO

in order to work, your script needs the password sent by the form, $algo, $cost variables and the salt generated when the password was registered, so you need to retrieve this last value from the database.

Right now your script is going to generate a new salt value to compare the password, value that's different from the original used for the hash generation. I hope is more clear now, English is not my main language.

Edited by cereal: n/a

0

Ever heard of the term - overhashing?? :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.