Jump to content

Hashing passwords the correct way?


Demonic

Recommended Posts

<?php

function generate_passhash($salt, $md5_password)
{
return md5(md5($salt).$md5_password);
}

function generate_salt($length=5)
{
$salt = '';
srand((double)microtime() * 1000000);
for ($i=0;$i<$length;$i++)
{
	$number = rand(33, 126);
	if ($number == '92')
	{
		$number = 93;
	}
	$salt .= chr($number);
}
return $salt;
}
?>

 

To use it you can do:

<?php

$salt = generate_salt($length=5);

$md5_password = md5($_POST['password']);

$hashed_password = generate_passhash($salt, $md5_password);

?>

 

You would put both the salt and hashed_password into the database.

 

When a user logs in, you have to grab their $salt from the database and do like the function does above:

 

$pass = md5(md5($row['salt']).$md5_password);

 

then do an if else

 

eg:

<?php

$password = strip_tags($_POST['password']);
$md5_password = md5($password);

$sql = "SELECT * FROM table WHERE username = '$username'";

$result = mysql_query($sql) or die(mysql_error());

$row = mysql_fetch_array($result);


$pass = md5(md5($row['salt']).$md5_password);

if($pass == $row['password'])
{
// Log the user in
}
else
{
// Wrong password
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.