Skip to content

Instantly share code, notes, and snippets.

Created March 27, 2013 07:23
Show Gist options
  • Save anonymous/5252382 to your computer and use it in GitHub Desktop.
Save anonymous/5252382 to your computer and use it in GitHub Desktop.
<?php
/**
* 加密 hash,生成发送给用户的 hash 字符串
*
* @param array $hash_data
* @param string $hash_key
* @return string
*/
function encode_hash($hash_data, $hash_key = false)
{
if (!$hash_data)
{
return false;
}
foreach ($hash_data as $key => $value)
{
$hash_string .= $key . "^]+" . $value . "!;-";
}
$hash_string = substr($hash_string, 0, - 3);
// 加密干扰码,加密解密时需要用到的 key
if (! $hash_key)
{
$hash_key = G_COOKIE_HASH_KEY;
}
// 加密过程
for ($i = 1; $i <= strlen($hash_string); $i ++)
{
$char = substr($hash_string, $i - 1, 1);
$keychar = substr($hash_key, ($i % strlen($hash_key)) - 2, 1);
$char = chr(ord($char) + ord($keychar));
$tmp_str .= $char;
}
$hash_string = base64_encode($tmp_str);
$hash_string = str_replace(array(
'+',
'/',
'='
), array(
'-',
'_',
'.'
), $hash_string);
return $hash_string;
}
/**
* 解密 hash,从用户回链的 hash 字符串解密出里面的内容
*
* @param string $hash_string
* @return array
*/
function decode_hash($hash_string, $hash_key = false)
{
if (!$hash_string)
{
return array();
}
// 加密干扰码,加密解密时需要用到的 Key
if (! $hash_key)
{
$hash_key = G_COOKIE_HASH_KEY;
}
// 解密过程
if (strpos($hash_string, '-') || strpos($hash_string, '_') || strpos($hash_string, '.'))
{
$hash_string = str_replace(array(
'-',
'_',
'.'
), array(
'+',
'/',
'='
), $hash_string);
}
$hash_string = base64_decode($hash_string);
for ($i = 1; $i <= strlen($hash_string); $i ++)
{
$char = substr($hash_string, $i - 1, 1);
$keychar = substr($hash_key, ($i % strlen($hash_key)) - 2, 1);
$char = chr(ord($char) - ord($keychar));
$tmp_str .= $char;
}
$hash_data = array();
$arr = explode('!;-', $tmp_str);
foreach ($arr as $value)
{
list($k, $v) = explode('^]+', $value);
if ($k)
{
$hash_data[$k] = $v;
}
}
return $hash_data;
}
@liukuan
Copy link

liukuan commented Mar 28, 2013

decode_hash 返回有个键为0的不能输出,检查发现,最下面的if 的变量k==0的时候肯定过去不。应该改为===null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment