这篇文章主要介绍了php实现的简单对称加密与解密方法,结合实例形式总结了常见的php对称加密与解密操作方法,需要的朋友可以参考下
本文实例讲述了php实现的简单对称加密与解密方法。分享给大家供大家参考,具体如下:
方法一:yii自带的加密方法
/**
* 加密
* @var string [要加密的值]
*/
$secretkey = "wwj";
$data = $res['u_id'];
$encrypteddata = yii::$app->getsecurity()->encryptbypassword($data, $secretkey);
/**
* 解密
* @var [type] [加密前的值]
*/
$aid = $req->get('uid');
$secretkey = "wwj";
$uid = yii::$app->getsecurity()->decryptbypassword($aid,$secretkey);
方法二:
/**
* 安全url编码
* @param type $data
* @return type
*/
function encode($data) {
return str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode(serialize($data)));
}
/**
* 安全url解码
* @param type $string
* @return type
*/
function decode($string) {
$data = str_replace(array('-', '_'), array('+', '/'), $string);
$mod4 = strlen($data) % 4;
($mod4) && $data .= substr('====', $mod4);
return unserialize(base64_decode($data));
}
方法三:
/**
* 加密
* @param [type] $code [description]
* @return [type] [description]
*/
public static function encrypt($code)
{
return urlencode(base64_encode(mcrypt_encrypt(mcrypt_rijndael_256, md5("key"), $code, mcrypt_mode_ecb, mcrypt_create_iv(mcrypt_get_iv_size(mcrypt_rijndael_256, mcrypt_mode_ecb), mcrypt_rand))));
}
/**
* 解密
* @param [type] $code [description]
* @return [type] [description]
*/
public static function decrypt($code)
{
return urldecode(mcrypt_decrypt(mcrypt_rijndael_256, md5("key"), base64_decode($code), mcrypt_mode_ecb, mcrypt_create_iv(mcrypt_get_iv_size(mcrypt_rijndael_256, mcrypt_mode_ecb), mcrypt_rand)));
}
方法四:
/**
* 简单对称加密
* @param string $string [需要加密的字符串]
* @param string $skey [加密的key]
* @return [type] [加密后]
*/
function encode($string = '', $skey = 'cxphp')
{
$strarr = str_split(base64_encode($string));
$strcount = count($strarr);
foreach (str_split($skey) as $key => $value)
$key < $strcount && $strarr[$key].=$value;
return str_replace(array('=', '+', '/'), array('o0o0o', 'o000o', 'oo00o'), join('', $strarr));
}
/**
* 简单对称解密
* @param string $string [加密后的值]
* @param string $skey [加密的key]
* @return [type] [加密前的字符串]
*/
function decode($string = '', $skey = 'cxphp')
{
$strarr = str_split(str_replace(array('o0o0o', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
$strcount = count($strarr);
foreach (str_split($skey) as $key => $value)
$key <= $strcount && isset($strarr[$key]) && $strarr[$key][1] === $value && $strarr[$key] = $strarr[$key][0];
return base64_decode(join('', $strarr));
}
相关推荐:
php对称加密函数实现数据的加密解密
php对称加密算法(des/aes)类代码
php对称加密算法示例_php教程
以上就是php实现对称加密与解密的详细内容。