PHP
$h2_rand = RndNum('12');
$h2_key = 'yytkjfgzmnklfgyy';
$h2_take = urlencode(ecbEncrypt($h2_key,PaddingPKCS7($h2_rand)));
function ecbEncrypt($key = "", $encrypt) {
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128 , MCRYPT_MODE_ECB), MCRYPT_RAND);
$decrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128 , $key, $encrypt, MCRYPT_MODE_ECB, $iv);
$encode = base64_encode($decrypted);
return $encode;
}
function PaddingPKCS7($input) {
$srcdata = $input;
$block_size = mcrypt_get_block_size('tripledes', 'ecb');
$padding_char = $block_size - (strlen($input) % $block_size);
$srcdata .= str_repeat(chr($padding_char),$padding_char);
return $srcdata;
}
function RndNum($n){
$rnd = "" ;
for($i=0;$i<$n;$i++)
$rnd .= floor(mt_rand(0,9));
return $rnd;
}
JS
/**
* 加密(需要先加载lib/aes/aes.min.js文件)https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.min.js
* @param word
* @returns {*}
*/
function encrypt(word){
var key = CryptoJS.enc.Utf8.parse("yytkjfgzmnklfgyy");
var srcs = CryptoJS.enc.Utf8.parse(word);
var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
return encrypted.toString();
}
//产生随机数函数
function RndNum(n){
var rnd="";
for(var i=0;i<n;i++)
rnd+=Math.floor(Math.random()*10);
return rnd;
}
-------------------------------------------
php
/**
*
* @param string $string 需要加密的字符串
* @param string $key 密钥
* @return string
*/
function encrypt($string, $key)
{
// openssl_encrypt 加密不同Mcrypt,对秘钥长度要求,超出16加密结果不变
$data = openssl_encrypt($string, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
return base64_encode($data);
}
/**
* @param string $string 需要解密的字符串
* @param string $key 密钥
* @return string
*/
function decrypt($string, $key)
{
return openssl_decrypt(base64_decode($string), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
}
/**
* 获取秘钥
* @return string
*/
function getSecretKey()
{
$str='xxx';//生成16位的字符窜
return $str;
}
JS:
<script type="text/javascript" src="./bower_components/crypto-js/crypto-js.js"></script>
<script type="text/javascript">
AesKey = 'xxxxx';//加密时用的key,跟php一样
message='xxxxxxx';//加密后的字符窜
var ECBOptions = {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
};
var key = CryptoJS.enc.Utf8.parse(AesKey);
var bytes = CryptoJS.AES.decrypt(message, key,ECBOptions);
var originalText = bytes.toString(CryptoJS.enc.Utf8);
console.log(originalText)
</script>
其他参考:https://www.cnblogs.com/lz2017/p/8046816.html