Question

I use the next code to to register a user: the name and the password, to store password I use crypt() and blowfish, it works, but I don't know how could descrypt the password in a login form

 $user = $_POST['user'];
$password = $_POST['pass'];
function cryptPass($input, $rounds = 5){
$salt = "";
$saltChars = array_merge(range('A','Z'), range('a','z'), range(0,9));
for($i=0; $i < 22; $i++) {
  $salt .= $saltChars[array_rand($saltChars)];
}
return crypt($input, sprintf('$2y$%02d$', $rounds) . $salt);
}
$password_hash = cryptPass($password);
$cSQL = "INSERT INTO USERDB (NAME, PASS) VALUES(?,?)";
$stmt = $db->prepare($cSQL);
$stmt->bind_param('ss', $name, $password_hash);
$stmt->execute();
$stmt->close();

And this is the function to descrypt the password, but it doesn't work, where's my mistake?

$user = $_POST['user'];
$password= $_POST['pass'];
function cryptPass($input, $rounds = 6)
{
$salt = "";
$saltChars = array_merge(range('A','Z'), range('a','z'), range(0,9));
for($i=0; $i < 22; $i++) {
  $salt .= $saltChars[array_rand($saltChars)];
}
return crypt($input, sprintf('$2x$%02d$', $rounds) . $salt);
}
$inputPass = $password;
$pass = $password;
$hashedPass = cryptPass($pass);
$passcrypt = crypt($inputPass, $hashedPass);
$stmt = $db->prepare("SELECT NAME, PASS
FROM  USERDB
WHERE NAME = ? AND PASS =?");
$stmt->bind_param('ss', $user, $passcrypt);
$stmt->execute();
$stmt->close();
Was it helpful?

Solution

Please do use the brand new password hash API in PHP 5.5. If you are on an older version, use https://github.com/ircmaxell/password_compat to get the same functions in PHP as old as version 5.3.7.

Usage is very simple:

When creating the account:

$hash = password_hash($password);

Store the hash in the database.

Verification:

if (password_verify($posted_password, $hash_from_db)) { // login }

See the documentation for more info!

Note that you have to read the hashed password from the database to get the salt it had used. That is also the error in your code. You cannot create a random salted hash when you are comparing the login password with the original hash. You have to compare the two hashes, and the login password has to be hashed with the same salt as the original password. Otherwise the hashes won't match.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top