I've only recently started working with PHP, but I've been stuck on this problem for hours now and searched everywhere for a solution with no success. Hopefully, someone here can help.
I'm writing a password verification function to verify the user's password with a SSHA hash from a database. Most of this code is taken from php.net
function asc2hex($temp) {
$len = strlen($temp);
$data = '';
for ($i=0; $i<$len; $i++) $data.=sprintf("%02x",ord(substr($temp,$i,1)));
return $data;
}
function validatePassword($password, $hash) {
if ((!isset($password)) || (!isset($hash)) || ($password=="") || ($hash=="")) {
return false;
}
// Verify SSHA hash
$ohash = base64_decode(substr($hash, 6));
$osalt = substr($ohash, 20);
$o_hex = asc2hex(substr($ohash, 0, 20));
$n_hex = sha1($password . $osalt);
echo 'o_hex (HEX) - "'.$o_hex.'"<br />';
echo 'n_hex (HEX) - "'.$n_hex.'"<br />';
echo '<br />';
if ($o_hex === $n_hex) {
return "true";
}
else {
return "false";
}
}
The problem is, validatePassword always returns true!
For example:
$userpass = "qbrtxpse";
if (validatePassword($userpass,"{SSHA}xXhNJfxymPwDTydUApoFBHuiQ7VqcFFL")) {
echo 'User authorized<br />';
}
else {
echo 'No user with those credentials found<br />';
}
This always results in 'User authorized', even though the echo's inside validatePassword show that $o_hex and $n_hex aren't the same.
I've tried converting $n_hex to ascii and comparing them that way, and I've tried strcmp($o_hex, $n_hex), but the result is always true!
Please help! What am I doing wrong?