Created
June 29, 2012 22:04
-
-
Save nikoheikkila/3020927 to your computer and use it in GitHub Desktop.
PHP: Utility class for hashing password securely
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Utility class for hashing password securely | |
* (source material from Net Tuts+) | |
* | |
* @author Niko Heikkilä | |
* @version 1.0 | |
*/ | |
class PasswordHash | |
{ | |
/** | |
* @var string $alg Algorithm for crypting | |
* @var string $cost The cost parameter | |
*/ | |
private static $alg = '$2a'; | |
private static $cost = '$10'; | |
/** | |
* Internal function for creating 22-character long salt | |
* | |
* @return string | |
*/ | |
public static function uniqueSalt() | |
{ | |
$salt = sha1( mt_rand() ); | |
return substr( $salt, 0, 22 ); | |
} | |
/** | |
* Generate a hash | |
* | |
* @param string $password Password to hash | |
* @return string | |
*/ | |
public static function hash( $password ) | |
{ | |
$full_salt = self::$alg . self::$cost . '$' . self::uniqueSalt(); | |
return crypt( $password, $full_salt ); | |
} | |
/** | |
* Compare password against a hash | |
* | |
* @param string $hash Hash value | |
* @param string $password Password from input | |
* @return boolean | |
*/ | |
public static function checkPassword( $hash, $password ) | |
{ | |
$full_salt = substr( $hash, 0, 29 ); | |
$new_hash = crypt( $password, $full_salt ); | |
/* TRUE if match */ | |
return ( $hash === $new_hash ); | |
} | |
} | |
/* End of file PasswordHash.class.php */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment