<?php
/**
* Desc: AES加密解密
* User: SenSen Wechat:1050575278
* Date: 2021/4/27
* Time: 14:14
*/
namespace sensen\services;
class AesService
{
protected static $method = "AES-128-CBC";
const KEY = 'fei1zui2you3jie!';
const IV = 'hello202105world';
/**
* 加密
* @param string|array $data 待加密
* @param string $key 秘钥
* @param string $iv 偏移量
* @return string|string[]|array
*/
public static function encrypt($data, $key=self::KEY, $iv=self::IV)
{
if(is_array($data)){
$res = [];
foreach ($data as $v){
$text = openssl_encrypt($v, static::$method, $key, OPENSSL_RAW_DATA, $iv);
$res[] = self::safetyBase64Encode($iv . $text);
}
}else{
$text = openssl_encrypt($data, static::$method, $key, OPENSSL_RAW_DATA, $iv);
$res = self::safetyBase64Encode($iv . $text);
}
return $res;
}
/**
* 解密
* @param string|array $text 待解密
* @param string $key 秘钥
* @param string $iv 偏移量
* @param false $login 是否为登录
* @return false|string|array
*/
public static function decrypt($text, $key=self::KEY, $iv=self::IV, $login=false) {
if(is_array($text)){
$data = [];
foreach ($text as $v){
$cipherText = self::safetyBase64Decode($v);
$cipherText = substr($cipherText, strlen($iv));
$data[] = openssl_decrypt($cipherText, static::$method, $key, OPENSSL_RAW_DATA, $iv);
}
}else{
$cipherText = self::safetyBase64Decode($text);
if($login){
//仅方便登录使用,登录时iv与key相同
$data = openssl_decrypt(base64_decode($text), static::$method, $key, OPENSSL_RAW_DATA, $iv);
}else{
$cipherText = substr($cipherText, strlen($iv));
$data = openssl_decrypt($cipherText, static::$method, $key, OPENSSL_RAW_DATA, $iv);
}
}
return $data;
}
/**
* base64安全编码
* @param string $text
* @return string|string[]
*/
public static function safetyBase64Encode($text)
{
$text = base64_encode($text);
$text = str_replace(['+','/'],['-','_'],$text);
return $text;
}
/**
* base64安全解码
* @param string $text
* @return false|string
*/
public static function safetyBase64Decode($text)
{
$text = str_replace(['-','_'],['+','/'],$text);
$text = base64_decode($text);
return $text;
}
}