Okay i am sitting here since hours scratching my head at this issue and i cannot figure out what is wrong. I am trying to encrypt a password via a random salt with crypt but when i try to login the has is always wrong.
Let me walk you through the script:
$cost = 10;
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
$salt = sprintf("$2y$%02d$", $cost) . $salt;
$hash = crypt($password, $salt);
echo $hash;
echo crypt($password, $hash);
Outputs the following with password as 'asdfgh':
$2y$10$865uru.sXJheD9TQKLDnZuTZfpAXv83UDuaSFfb.G2qIxBzEb1pOi
$2y$10$865uru.sXJheD9TQKLDnZuTZfpAXv83UDuaSFfb.G2qIxBzEb1pOi
The hash in the database looks like this:
$2y$10$865uru.sXJheD9TQKLDnZuTZfpAXv83UDuaSFfb.G2qIxBzEb1pOi
For the login script we have the following code for testing purposes:
echo $data->hash . '<br>';
echo crypt('asdfgh', $data->hash) . '<br>';
echo crypt('asdfgh', '$2y$10$865uru.sXJheD9TQKLDnZuTZfpAXv83UDuaSFfb.G2qIxBzEb1pOi');
And that outputs the following:
$2y$10$865uru.sXJheD9TQKLDnZuTZfpAXv83UDuaSFfb.G2qIxBzEb1pOi
$2y$10$865uru.sXJheD9TQKLDnZuRRPJQwjWh2PGgtntpcsnRaGzvv5Sfte
$2y$10$865uru.sXJheD9TQKLDnZuRRPJQwjWh2PGgtntpcsnRaGzvv5Sfte
While the database string is still correct, and even by passing the correct string manually to the function the generated hash is different. I am out of solutions ...
If anyone could help me i would very much appreciate it.
PHP Version 5.4.16 on Windows
UPDATE: Here is the updated snippets with the salt:
$cost = 10;
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
$salt = sprintf("$2y$%02d$", $cost) . $salt;
$hash = crypt($password, $salt);
$data = array(
'id' => '',
'username' => $username,
'hash' => $hash,
'email' => $email,
'salt' => $salt,
);
$this->mdl_registration->_insert($data);
$this->load->view('registration_submit');
For the login script:
function check_login($password) {
$username = $this->input->post('username');
$result = $this->get_where_custom('username', $username);
foreach($result->result() as $data) {
echo $data->hash . '<br>';
echo crypt('asdfgh', $data->salt) . '<br>';
$test = crypt($password, $data->salt);
if($test == $data->hash) {
return TRUE;
}
else {
$this->form_validation->set_message('check_login', 'Invalid Username and / or Password');
return FALSE;
}
}
}
The echos for testing purposes return the following:
$2y$10$ZgbOXM18lArDu/u/Ftsdr.t7VPnLsqLJdC2Dum8pl/flW8LmnnUoS
$2y$10$ZgbOXM18lArDu/u/Ftsdr.s5N5juHB/zq/5SN/7oFAjn9CZKjI9H6