本文实例讲述了php加密解密类。分享给大家供大家参考。具体分析如下:
这段代码支持 数组加密 , 密文有效期, 各种对称加密
其中参数如下:
* @use ption::en($string, $key);
* @param string $string 需要加密的字串
* @param string $skey 密钥
* @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效
* @return string
1. php代码如下:
/*
* -工具库-加密解密码
*/
class ption
{
private static $original = array('=', '+', '/');
private static $later = array('o0o0o', 'o0o0o', 'oo00o');
function __construct()
{
}
private static function md5($skey = '')
{
$skey = $skey ? $skey : 'ui' ; //uicms::_config('security/authkey');
return md5(substr($skey, 0, 16));
}
/**
* @use ption::en($string, $key);
* @param string $string 需要加密的字串
* @param string $skey 密钥
* @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效
* @return string
*/
static public function en($string = '', $skey = '', $expiry=0)
{
if( is_array( $string ) )
{
$string = json_encode($string); // uicms::json($string, true, 'en');
}
$string = str_pad($expiry ? $expiry + time : 0, 10, 0).$string;
$strarr = str_split(base64_encode($string));
$strcount = count($strarr);
$skey = static::md5($skey);
foreach (str_split($skey) as $key => $value)
{
$key < $strcount && $strarr[$key].=$value;
}
return str_replace(self::$original, self::$later, join('', $strarr));
}
/**
* @use ption::de($string, $key);
* @param string $string 需要解密的字串
* @param string $skey 密钥
* @return string
*/
static public function de($string = '', $skey = '')
{
$strarr = str_split(str_replace(self::$later,self::$original,$string),2);
$strcount = count($strarr);
$skey = static::md5($skey);
foreach (str_split($skey) as $key => $value)
{
$key < $strcount && $strarr[$key][1] === $value && $strarr[$key] = $strarr[$key][0];
}
$result = base64_decode(join('', $strarr));
if(substr($result, 0, 10) == 0 || substr($result, 0, 10) - time > 0)
{
return substr($result, 10);
}
else
{
return false;
}
}
}
2. 用法如下:
$str['username'] = 'oschina'; $str['pw'] = '123456'; $str['huoxin'] = '!@#$%^&'; echo "string : " . $str . " <br />"; echo "encode : " . ($enstring = ption::en($str)) . '<br />'; echo "decode : " . ption::de($enstring);
希望本文所述对大家的php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!