Skip to content

Instantly share code, notes, and snippets.

@zhouyl
Created July 2, 2014 09:08
Show Gist options
  • Select an option

  • Save zhouyl/f4a7b53cea3103d5a6d9 to your computer and use it in GitHub Desktop.

Select an option

Save zhouyl/f4a7b53cea3103d5a6d9 to your computer and use it in GitHub Desktop.
密码 HASH 处理
<?php
/**
* 密码 HASH 处理
*/
class Password
{
/**
* 密码哈希盐模
*
* @var array
*/
public static $saltPattern = array(1, 3, 5, 9, 14, 15, 20, 21, 28, 30);
/**
* 密码哈希加密方法
*
* @var string
*/
public static $hashMethod = 'sha1';
/**
* 查找 salt
*
* @param string $password
* @return string
*/
public static function salt($passwd)
{
$salt = '';
$pattern = Password::$saltPattern;
foreach ($pattern as $i => $offset) {
// Find salt characters, take a good long look...
$salt .= substr($password, $offset + $i, 1);
}
return $salt;
}
/**
* 创建密码
*
* @param string $password
* @param boolean $salt
* @return string
*/
public static function create($passwd, $salt = false)
{
if ($salt === false) {
// Create a salt seed, same length as the number of offsets in the pattern
$salt = substr(hash('sha1', uniqid(null, true)), 0, count(Password::$saltPattern));
}
// Password hash that the salt will be inserted into
$hash = Password::hash($salt . $password);
// Change salt to an array
$salt = str_split($salt, 1);
// Returned password
$password = '';
// Used to calculate the length of splits
$last_offset = 0;
foreach (Password::$saltPattern as $offset) {
// Split a new part of the hash off
$part = substr($hash, 0, $offset - $last_offset);
// Cut the current part out of the hash
$hash = substr($hash, $offset - $last_offset);
// Add the part to the password, appending the salt character
$password .= $part . array_shift($salt);
// Set the last offset to the current offset
$last_offset = $offset;
}
// Return the password, with the remaining hash appended
return $password . $hash;
}
/**
* Perform a hash, using the configured method.
*
* @param string $str
* @return string
*/
public static function hash($str)
{
return hash(Password::$hashMethod, $str);
}
/**
* 比较密码是否一致
*
* @param string $hashPassword
* @param string $password
*/
public static function match($hashPassword, $password)
{
return (Password::create($password, Password::salt($hashPassword)) === $hashPassword);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment