AES-256 encryption and decryption in PHP and JS
PHP:
class clsAES { private $key = ''; private $iv = ''; public function __construct($key, $iv) { $this->key = md5($key); $this->iv = $iv; } public function encrypt($data) { $cryptText = openssl_encrypt($data,"aes-256-cbc",$this->key ,OPENSSL_RAW_DATA,$this->iv); return base64_encode($cryptText); } public function decrypt($data) { $cryptText = base64_decode($data); return trim(openssl_decrypt($cryptText, 'aes-256-cbc', $this->key , OPENSSL_RAW_DATA,$this->iv)); } }
JS:
Vue:
import CryptoJS from 'crypto-js' const KEY = '5NmhVXqSro6j9eyNO3bzw'; const IV = '1234567890123456'; function getAesString(data, key, iv) {//加密 var key_hash = CryptoJS.MD5(key).toString(); var key = CryptoJS.enc.Utf8.parse(key_hash); var iv = CryptoJS.enc.Utf8.parse(iv); var encrypted = CryptoJS.AES.encrypt(data, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); return encrypted.toString(); //返回的是base64格式的密文 } function getDAesString(encrypted, key, iv) {//解密 var key_hash = CryptoJS.MD5(key).toString(); var key = CryptoJS.enc.Utf8.parse(key_hash); var iv = CryptoJS.enc.Utf8.parse(iv); var decrypted = CryptoJS.AES.decrypt(encrypted, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); return decrypted.toString(CryptoJS.enc.Utf8); } export function getEAES(data) { //加密 var encrypted = getAesString(data, KEY, IV); // var encrypted1 = CryptoJS.enc.Utf8.parse(encrypted); return encrypted; } export function getDAES(data) {//解密 return getDAesString(data, KEY, IV); }
//模块初始化 var init=function () { key = CryptoJS.enc.Utf8.parse(CryptoJS.MD5(ym.hezubao).toString()); iv = CryptoJS.enc.Utf8.parse(CryptoJS.MD5(key).toString().substr(0,16)); } function encrypt(data) { var encrypted=''; if(typeof(data)=='string') { encrypted = CryptoJS.AES.encrypt(data,key,{ iv : iv, mode : CryptoJS.mode.CBC, padding : CryptoJS.pad.ZeroPadding }); }else if(typeof(data)=='object'){ data = JSON.stringify(data); encrypted = CryptoJS.AES.encrypt(data,key,{ iv : iv, mode : CryptoJS.mode.CBC, padding : CryptoJS.pad.Pkcs7 //ZeroPadding }) } return encrypted.toString(); } /*AES解密 * param : message 密文 * return : decrypted string 明文 */ function decrypt(message) { decrypted=''; decrypted=CryptoJS.AES.decrypt(message,key,{ iv : iv, mode : CryptoJS.mode.CBC, padding : CryptoJS.pad.ZeroPadding }); return decrypted.toString(CryptoJS.enc.Utf8); }