AES 加密解密 CryptoJS + php 方案
本来一直用 jwt,由于其明文串不管是否 Verified 通过都能拿到初始数据,不适合做token,满足不了当前业务需求。最终选择AES,php 端AES的实现大体就是mcrypt 或者 openssl。这里选择openssl,个人感觉openssl实现起来代码更加简洁一点。
直接上代码先
- PHP 服务端
/**
* AES加密
* @param array $data 待转换报文
* @param string $key 加密KEY
* @param string $iv 偏移量
* @param string $method 方法,参考资料一
* @return string
*/
public static function opensslEncrypt(
$data,
$key,
$iv = '',
$method = 'AES-256-CBC'
)
{
$plaintext = json_encode($data);
$str = openssl_encrypt($plaintext, $method, $key, 0, $iv);
$search = ['+', '/'];
$replace = ['-', '_'];
return str_replace($search, $replace, $str);
}
/**
* AES解密
* @param string $encrypt 待转换密文
* @param string $key 加密KEY
* @param string $iv 偏移量
* @param string $method 方法,参考资料一
* @return array
*/
public static function opensslDecrypt(
$encrypt,
$key,
$iv = '',
$method = 'AES-256-CBC'
)
{
$replace = ['+', '/'];
$search = ['-', '_'];
$str = openssl_decrypt(str_replace($search, $replace, $encrypt), $method, $key, OPENSSL_ZERO_PADDING, $iv);
$plaintext = substr($str, 0, strrpos($str, "}") + 1);
return json_decode($plaintext, true);
}
- JS 端代码
感谢 symfony/webpack-encore-bundle 一如既往强大的symfony提供的 encore,直接使用webpack很方便集成Crypto-JS
// 这里需要自行npm安装 crypto-js
import CryptoJS from 'crypto-js';
let key = '654mca0l38b489d9f306a5b8e105334b',
iv = 'c5defg0045222c52';
/**
* 加密
* @param string work 待加密报文
* @return string
*/
export function encrypt (word) {
let encrypt = CryptoJS.AES.encrypt(word,CryptoJS.enc.Utf8.parse(key),{
iv:CryptoJS.enc.Utf8.parse(iv),
mode:CryptoJS.mode.CBC,
padding:CryptoJS.pad.Pkcs7
})
return encrypt.toString();
}
/**
* 解密
* @param string work 待解密报文
* @return string
*/
export function decrypt (word) {
let decrypted = CryptoJS.AES.decrypt(word,CryptoJS.enc.Utf8.parse(key),{
iv:CryptoJS.enc.Utf8.parse(iv),
mode:CryptoJS.mode.CBC,
padding:CryptoJS.pad.Pkcs7
})
return decrypted.toString(CryptoJS.enc.Utf8)
}
-
资料一
method 官网提供很多种,常用的不多
- AES-128-CBC
- AES-128-CFB
- AES-128-CFB1
- AES-128-CFB8
- AES-128-OFB
- AES-192-CBC
- AES-192-CFB
- AES-192-CFB1
- AES-192-CFB8
- AES-192-OFB
- AES-256-CBC
- AES-256-CFB
- AES-256-CFB1
- AES-256-CFB8
- AES-256-OFB
- BF-CBC
- BF-CFB
- BF-OFB
- CAST5-CBC
- CAST5-CFB
- CAST5-OFB
- IDEA-CBC
- IDEA-CFB
- IDEA-OFB
- aes-128-cbc
- aes-128-cfb
- aes-128-cfb1
- aes-128-cfb8
- aes-128-ofb
- aes-192-cbc
- aes-192-cfb
- aes-192-cfb1
- aes-192-cfb8
- aes-192-ofb
- aes-256-cbc
- aes-256-cfb
- aes-256-cfb1
- aes-256-cfb8
- aes-256-ofb
- bf-cbc
- bf-cfb
- bf-ofb
- cast5-cbc
- cast5-cfb
- cast5-ofb
- idea-cbc
- idea-cfb
- idea-ofb
希望对大家有帮忙,
网友评论