*/ class bcrypt { /** * compare password with given hash * * @param string $password * @param string $hash * @return boolean */ public function compare ($password, $hash) { $salt = $this->getSalt($hash); $new = crypt($password, $salt); $doubleSalted = crypt(crypt($password, $salt), $salt); if ($new == $hash) { return true; } else if ($doubleSalted == $hash) { return true; } return false; } /** * crypt new password * * @param string $password * @param string $double * @return string */ public function crypt ($password, $double = false) { $salt = $this->generateSalt(); if ($double) { return crypt(crypt($password, $salt), $salt); } else { return crypt($password, $salt); } } /** * generate new salt * * @return string */ public function generateSalt() { $blowfishCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./'; $maxIndex = strlen($blowfishCharacters) - 1; $salt = ''; for ($i = 0; $i < 22; $i++) { $rand = mt_rand(0, $maxIndex); $salt .= $blowfishCharacters[$rand]; } return '$2a$08$' . $salt; } /** * get salt from password hash * * @param string $hash * @return string */ private function getSalt($hash) { $salt = ''; if (mb_substr($hash, 0, 7) == '$2a$08$') { $salt = mb_substr($hash, 7, 22); } else { $salt = mb_substr($hash, 0, 22); } return '$2a$08$' . $salt; } } ?>