标题: PHP openssl 解密 中文乱码
时间: 2019-12-24发布,2022-09-21修改
js加密为:
<?php
var IV = '1234567890123412';
var KEY = '201707eggplant99'
/**
* 加密
*/
function encrypt(str) {
key = CryptoJS.enc.Utf8.parse(KEY);// 秘钥
var iv= CryptoJS.enc.Utf8.parse(IV);//向量iv
var encrypted = CryptoJS.AES.encrypt(str, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7});
return encrypted.toString();
}
console.log(encrypt("你好啊啊啊啊啊。,,,,123123-="))
<?php
$b= openssl_decrypt(base64_decode('TXw083cvDY8dDo+K9/1E0XpM8V4KERsMmRy9gCsWmrADKMtf/+S8skaHUHsftwRMOBucJdiWDlaEdVwC6QSnkg=='),"AES-128-CBC",$this->key,OPENSSL_RAW_DATA,$this->hex_iv);
echo htmlspecialchars($b);
//解密后
// 浣犲ソ鍟婂晩鍟婂晩鍟娿€傦紝,,,123123-=
iconv gbk与uft8都转过了不行的
『回复列表(3|隐藏机器人聊天)』
<?php
declare(strict_types=1);
namespace app\common\unit;
use think\Exception;
/**
* Class AES128CBC
* @package app\common\unit
* Auth
*/
class AES128CBC
{
private $vi='123456789abcdefg'; //VI需要指定16位
private $key='';
private $method='AES-128-CBC';
public $error;
public function __construct(string $key='',$vi='')
{
if(!empty($vi)){
$this->vi=$vi;
}
if(empty($key)){
throw new Exception('AES加密必须传入key' );
}
$this->key=$key;
}
public function encrypt($str){
$decode = base64_encode(openssl_encrypt($str,$this->method,$this->key,OPENSSL_RAW_DATA,$this->vi));
if($decode){
return $decode;
}
$this->error=__CLASS__.'解密失败!'.json_encode(['vi'=>$this->vi,'key'=>$this->key]);
throw new Exception($this->error);
}
public function decrypt($str){
$encode = openssl_decrypt(base64_decode($str),$this->method,$this->key,OPENSSL_RAW_DATA,$this->vi);
if($encode){
return $encode;
}
$this->error=__CLASS__.'加密失败!'.json_encode(['vi'=>$this->vi,'key'=>$this->key]);;
throw new Exception($this->error);
}
public function getError(){
return $this->error;
}
public function setVi($vi){
$this->vi=$vi;
return $this;
}
public function setKey($key){
$this->key=$key;
return $this;
}
public static function encode($k,$vi,$data){
$_t=new self($k,$vi);
return $_t->encrypt($data);
}
public static function decode($k,$vi,$data){
$_t=new self($k,$vi);
return $_t->decrypt($data);
}
}
<script type="text/javascript" src="js/aes.js"></script>
function aesEncrypt(str) {
var key = CryptoJS.enc.Utf8.parse(window.env.aes_key);
var iv = CryptoJS.enc.Utf8.parse(window.env.aes_vi);
var encrypted = CryptoJS.AES.encrypt(str,key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.Pkcs7});
if(encrypted==null){
throw "无法加密数据:"+str;
}
return encrypted.toString();
}
// 解密
function aesDecrypt(str) {
var key = CryptoJS.enc.Utf8.parse(window.env.aes_key);
var iv = CryptoJS.enc.Utf8.parse(window.env.aes_vi);
var decrypted = CryptoJS.AES.decrypt(str,key,{iv:iv,padding:CryptoJS.pad.Pkcs7});
if(decrypted==null){
throw "无法解密数据:"+str;
}
return decrypted.toString(CryptoJS.enc.Utf8);
}