<?php
class Cookie
{
/**`在这里插入代码片`
* 解密已经加密了的cookie
*
* @param string $encryptedText
* @return string
*/
private static function _decrypt($encryptedText)
{
//base64解码
$c = base64_decode($encryptedText);
//获取IV字段的长度
$ivlen = openssl_cipher_iv_length($cipher="AES-256-CBC");
//从密文数据中截取IV字段
$iv = substr($c, 0, $ivlen);
//计算加密用到的Key
$key = hash('md5','woshixiaoludan');
//获取Hmac值
$hmac = substr($c, $ivlen, $sha2len=32);
//获取加密后的密文数据值
$ciphertext_raw = substr($c, $ivlen+$sha2len);
//进行密文解密
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
//重新进行Hmac值的计算
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
//如果解密的Hmac值与计算的Hmac值一致,则表示数据没有被篡改
if (hash_equals($hmac, $calcmac))//PHP 5.6+ timing attack safe comparison
{
//如果数据的完整性通过检验,则返回解密后的值
return ($original_plaintext);
}
}
/**
* 加密cookie
*
* @param string $plainText
* @return string
*/
private static function _encrypt($plainText)
{
//获取IV的长度
$ivlen = openssl_cipher_iv_length($cipher="AES-256-CBC");
//通过伪随机数生成器生成IV长度的字符串
$iv = openssl_random_pseudo_bytes($ivlen);
//获取加密时用到的key
$key = hash('md5','woshixiaoludan');
//对数据进行加密
$ciphertext_raw = openssl_encrypt($plainText, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
//计算数据的Hmac值
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
//将iv、hmac、加密数据进行拼接,然后使用base64编码
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
return trim($ciphertext);
}
/**
* 删除cookie
*
* @param array $args
* @return boolean
*/
public static function del($args)
{
$name = $args['name'];
$domain = isset($args['domain']) ? $args['domain'] : null;
return isset($_COOKIE[$name]) ? setcookie($name, '', time() - 86400, '/', $domain) : true;
}
/**
* 通过此方法拿到指定cookie的值
*
* @param string $name
*/
public static function get($name)
{
return isset($_COOKIE[$name]) ? self::_decrypt($_COOKIE[$name]) : null;
}
/**
* 设置Cookie
* @param $args
* @return bool
*/
public static function set($args)
{
$name = $args['name'];
$value= self::_encrypt($args['value']);
$expire = isset($args['expire']) ? $args['expire'] : null;
$path = isset($args['path']) ? $args['path'] : '/';
$domain = isset($args['domain']) ? $args['domain'] : null;
$secure = isset($args['secure']) ? $args['secure'] : 0;
return setcookie($name, $value, $expire, $path, $domain, $secure);
}
}
PHP实现COOKIE加解密(复制粘贴就能用)
最新推荐文章于 2023-01-18 23:23:37 发布