crypto加密:后端PHP加密,前端JS解密
前端工作:使用cdn加载:
https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
string 要加密/解密的字符串
code 秘钥字符串
operation 默认false表示加密,传入true表示解密
// 加密解密方法:string-需要解密的字段 code-约定的密钥 operation 默认false表示加密,传入true表示解密
function secret(string, code, operation) {
code = CryptoJS.MD5(code).toString()
var iv = CryptoJS.enc.Utf8.parse(code.substring(0, 16))
var key = CryptoJS.enc.Utf8.parse(code.substring(16))
if (operation) {
return CryptoJS.AES.decrypt(string, key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7
}).toString(CryptoJS.enc.Utf8)
}
return CryptoJS.AES.encrypt(string, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}).toString()
}
var $string = '6sFQ6gfswps0tZG5IRxk';
var $code = '1234';
var string = secret($string,$code,true);
console.log(string);
php
function gptKey($string,$code,$operation=false){
$code = md5($code);
$iv = substr($code,0,16);
$key = substr($code,16);
if($operation){
$str = openssl_decrypt(base64_decode($string),"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv);
}else{
$str = base64_encode(openssl_encrypt($string,"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv));
}
return urlencode($str);
}