PHP类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
class
AES
{
/**
*
* @param string $string 需要加密的字符串
* @param string $key 密钥
* @return string
*/
public
static
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
*/
public
static
function
decrypt(
$string
,
$key
)
{
return
openssl_decrypt(
base64_decode
(
$string
),
'AES-128-ECB'
,
$key
, OPENSSL_RAW_DATA);
}
/**
* 获取秘钥
* @return string
*/
public
static
function
getSecretKey()
{
$str
=
'xxx'
;
//生成16位的字符窜
return
$str
;
}
}
|
JS的写法:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<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>
|