在之前前端尝试使用过 crypto-js,但是一直报 Malformed UTF-8 data
,尝试了百度搜索第一页的所有方案无效,于是尝试在 crypto-js 库 github 的 issue 寻找方案,但这个问题在 2020年3月3号被提出,到了目前还没有被解决。无奈之下只能在 github上查找相关的库,直到找到了 https://github.com/TCWTEAM/CrypJS.git,本文的前端代码由 CrypJS 修改而来
key 的长度需要注意一下,为 16 位时,会报key无效。32 是可以的
/**
* aes-256-cbc 加密
* @throws \Exception
*/
function encode(string $data, string $key, string $iv = null): array
{
$iv = $iv ?? uniqid() . '000';
if (strlen($iv) != 16) {
throw new \Exception('openssl_encrypt(): IV passed is only 13 bytes long, cipher expects an IV of precisely 16 bytes');
}
$data = openssl_encrypt($data, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
return [
'data' => base64_encode($data),
'iv' => $iv,
];
}
/**
* aes-256-cbc 解密
*/
function decryption(data, pass, iv) {
const crypto = require('crypto');
let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(pass), Buffer.from(iv));
let decryptedstring = decipher.update(Buffer.from(data, 'base64'));
let finalstring = Buffer.concat([decryptedstring, decipher.final()]);
console.log('obj = ', finalstring.toString());
return finalstring.toString();
}