/**
* 对称加密类
*
* 依赖:openssl扩展;
*
* 加解密要指定对应的密钥$key,加密结果是经过base64编码的。
*
* 例如:
* use \leyangjun\Lib\Crypt;
* $key = 'XXXXXXXXXXXXXXXX'; //密钥
* $data = '明文';
* $cipherText = Crypt::encrypt($data, $key); //加密
* $text = Crypt::decrypt($cipherText, $key); //解密
*/
class Crypt
{
protected static $method = 'AES-256-CBC';
public static function encrypt($data, $key)
{
$ivLen = openssl_cipher_iv_length(static::$method);
$iv = openssl_random_pseudo_bytes($ivLen);
$text = openssl_encrypt($data, static::$method, $key, OPENSSL_RAW_DATA, $iv);
return self::safetyBase64Encode($iv . $text);
}
public static function decrypt($text, $key)
{
$cipherText = self::safetyBase64Decode($text);
$ivLen = openssl_cipher_iv_length(static::$method);
$iv = substr($cipherText, 0, $ivLen);
if (strlen($iv) != $ivLen) {
$iv = substr(str_pad($iv, $ivLen, '0'), 0, $ivLen);
}
$cipherText = substr($cipherText, $ivLen);
$data = openssl_decrypt($cipherText, static::$method, $key, OPENSSL_RAW_DATA, $iv);
return $data;
}
public static function safetyBase64Encode($text)
{
$text = base64_encode($text);
$text = str_replace(['+','/'],['-','_'],$text);
return $text;
}
public static function safetyBase64Decode($text)
{
$text = str_replace(['-','_'],['+','/'],$text);
$text = base64_decode($text);
return $text;
}
}
以上每次请求的都是唯一的字符串值,会发现不适合业务逻辑判断处理,
比如:
$name = '乐杨俊',加密后为:‘Y2FkOWJhZDJkMzYwZGYwY2NiZTRjYTFiZDFmNTU1NGPYX6lCj’,能后数据入库了
下次,你要校验$name = '乐杨俊' 在库中是否存在,你会发现,上面的方法又会给你生成一个新的字 串‘X2FkOWJhZDJkMzYwDWERHJKHUHIUGYUTSDSFCMNXVBSWUY’,
为什么呢?
因为openssl_encrypt函数跌五个参数iv是动态的,我们把它写死就行,这样每次$name生成的值都是相同的
改造代码如下
class CryptTwo
{
protected static $method = 'AES-256-CBC';
const KEY = '3ad43742ed26e2e7a24d37464410179c';//bin2hex(openssl_random_pseudo_bytes(16));
const IV = 'cad9bad2d360df0ccbe4ca1bd1f5554c';
/**
* 加密
* @param $data
* @param string $key
* @return mixed|string
*/
public static function encrypt($data, $key = self::KEY)
{
$iv = self::IV;
$text = openssl_encrypt($data, static::$method, $key, OPENSSL_RAW_DATA, $iv);
return self::safetyBase64Encode($iv . $text);
}
/**
* 解密
* @param $text
* @param string $key
* @return string
*/
public static function decrypt($text, $key = self::KEY)
{
$cipherText = self::safetyBase64Decode($text);
$ivLen = openssl_cipher_iv_length(static::$method);
$iv = substr($cipherText, 0, $ivLen);
$cipherText = substr($cipherText, strlen(self::IV));
$data = openssl_decrypt($cipherText, static::$method, $key, OPENSSL_RAW_DATA, $iv);
return $data;
}
public static function safetyBase64Encode($text)
{
$text = base64_encode($text);
$text = str_replace(['+', '/'], ['-', '_'], $text);
return $text;
}
public static function safetyBase64Decode($text)
{
$text = str_replace(['-', '_'], ['+', '/'], $text);
$text = base64_decode($text);
return $text;
}
}