Add password management and the associated tests
git-svn-id: https://svn.fournier38.fr/svn/ProgSVN/trunk@4137 bf3deb0d-5f1a-0410-827f-c0cc1f45334c
This commit is contained in:
48
password.php
Normal file
48
password.php
Normal file
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
/** A class to manage the password hashing
|
||||
*/
|
||||
class password
|
||||
{
|
||||
/** Crypt the password with the best algorithm available
|
||||
* @param string $password The password to crypt
|
||||
* @return string The hashed password
|
||||
*/
|
||||
static public function cryptPasswd ($password)
|
||||
{
|
||||
if (! function_exists ("openssl_random_pseudo_bytes"))
|
||||
throw new \Exception (dgettext ("domframework",
|
||||
"No PHP support for openssl_random_pseudo_bytes"),
|
||||
500);
|
||||
if (! is_string ($password) && ! is_integer ($password))
|
||||
throw new \Exception (dgettext ("domframework",
|
||||
"Invalid clear password provided to be crypted : not a string"), 403);
|
||||
$cost = 11;
|
||||
$salt = substr (base64_encode (openssl_random_pseudo_bytes (17)), 0, 22);
|
||||
$salt = str_replace ("+", ".", $salt);
|
||||
$param = '$'.implode ('$', array (
|
||||
"2y", //select the most secure version of blowfish (>=PHP 5.3.7)
|
||||
str_pad ($cost, 2, "0", STR_PAD_LEFT), //add the cost in two digits
|
||||
$salt //add the salt
|
||||
));
|
||||
//now do the actual hashing
|
||||
return crypt ($password, $param);
|
||||
}
|
||||
|
||||
/** Check if the clear password is valid against the hashed one
|
||||
* @param string $clear The clear password
|
||||
* @param string $hashed The hashed password
|
||||
* @return boolean true if the password correspond to the hash
|
||||
*/
|
||||
static public function checkPassword ($clear, $hashed)
|
||||
{
|
||||
if (! is_string ($clear))
|
||||
throw new \Exception (dgettext ("domframework",
|
||||
"Invalid clear password provided to be checked : not a string"), 403);
|
||||
if (! is_string ($clear))
|
||||
throw new \Exception (dgettext ("domframework",
|
||||
"Invalid hashed password provided to be checked : not a string"), 403);
|
||||
if (crypt ($clear, $hashed) === $hashed)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user