lithium\security\Password::hash()
Hashes a password using PHP's crypt()
and an optional salt. If no
salt is supplied, a cryptographically strong salt will be generated
using lithium\security\Password::salt()
.
Using this function is the proper way to hash a password. Using naïve methods such as sha1 or md5, as is done in many web applications, is improper due to the lack of a cryptographically strong salt.
Using lithium\security\Password::hash()
ensures that:
- Two identical passwords will never use the same salt, thus never resulting in the same hash; this prevents a potential attacker from compromising user accounts by using a database of most commonly used passwords.
- The salt generator's count iterator can be increased within Lithium or your application as computer hardware becomes faster; this results in slower hash generation, without invalidating existing passwords.
Usage:
// Hash a password before storing it:
$hashed = Password::hash($password);
// Check a password by comparing it to its hashed value:
$check = Password::check($password, $hashed);
// Use a stronger custom salt:
$salt = Password::salt('bf', 16); // 2^16 iterations
$hashed = Password::hash($password, $salt); // Very slow
$check = Password::check($password, $hashed); // Very slow
// Forward/backward compatibility
$salt1 = Password::salt('bf', 6);
$salt2 = Password::salt('bf', 12);
$hashed1 = Password::hash($password, $salt1); // Fast
$hashed2 = Password::hash($password, $salt2); // Slow
$check1 = Password::check($password, $hashed1); // True
$check2 = Password::check($password, $hashed2); // True
Parameters
-
string
$password
The password to hash.
-
string
$salt
Optional. The salt string.
Returns
stringThe hashed password. The result's length will be:
- 60 chars long for Blowfish hashes
- 20 chars long for XDES hashes
- 34 chars long for MD5 hashes
Links
Source
public static function hash($password, $salt = null) {
return crypt($password, $salt ?: static::salt());
}