PHP7.1
以后mcrypt_encrypt
将会被废弃,所以我们使用openssl_decrypt
和openssl_encrypt
的组合方式实现AES
加密实现PHP/js
互通加密/解密。
一、PHP加密解密
<?PHP $data = 'ABCDEFGH'; $key = "1234567898882222"; $iv = '8NONwyJtHesysWpM';// 加密 $encode = base64_encode(openssl_encrypt($data,"AES-128-CBC",$key,true,$iv));// 解密 $decode = openssl_decrypt(base64_decode($encode),"AES-128-CBC",$key,true,$iv); $lists = array("encode"=>$encode,"decode"=>$decode,"iv"=>$iv,"key"=>$key,"data"=>$data); var_dump($lists);?>
二、js端的加密解密
js
端使用CryptoJS
封装的库。
<!DOCTYPE html> <html> <head> <title>AES</title></head> <script type="text/javascript" src="http://react.file.alimmdn.com/aes.js"></script> <body> <script>var IV = '8NONwyJtHesysWpM'; var KEY = '1234567898882222'; var data = 'ABCDEFGH'; // 加密 function encrypt(str) { var key = CryptoJS.enc.Utf8.parse(KEY); var iv = CryptoJS.enc.Utf8.parse(IV); var encrypted = CryptoJS.AES.encrypt(str, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); return encrypted.toString(); } // 解密 function decrypt(str) { var key = CryptoJS.enc.Utf8.parse(KEY); var iv = CryptoJS.enc.Utf8.parse(IV); var decrypted = CryptoJS.AES.decrypt(str, key, { iv: iv, padding: CryptoJS.pad.Pkcs7 }); return decrypted.toString(CryptoJS.enc.Utf8); } var encode = encrypt(data); var decode = decrypt(encode); console.log(JSON.stringify({ "encode": encode, "decode": decode, "iv": IV, "key": KEY, "data": data }));</script> </body> </html>原文链接:https://www.f2er.com/php/477224.html