Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Created June 29, 2012 22:04
Show Gist options
  • Save nikoheikkila/3020927 to your computer and use it in GitHub Desktop.
Save nikoheikkila/3020927 to your computer and use it in GitHub Desktop.
PHP: Utility class for hashing password securely
<?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