PHP使用AES方式进行加密、解密。
使用openssl_encrypt函数进行加密:
openssl_encrypt ( string $data , string $method , string $key [, int $options = 0 [, string $iv = "" [, string &$tag = NULL [, string $aad = "" [, int $tag_length = 16 ]]]]] ) : string
参数$method - 加密方法,可选值DES-ECB、DES-CBC、DES-CTR、DES-OFB、DES-CFB
参数$options - 操作,可选值0、OPENSSL_RAW_DATA=1、OPENSSL_ZERO_PADDING=2、OPENSSL_NO_PADDING=3
OPENSSL_RAW_DATA方式,会用PKCS#7进行补位
OPENSSL_ZERO_PADDING方式,会用0进行补位
与前端交互只能使用OPENSSL_RAW_DATA和OPENSSL_ZERO_PADDING方式
参数$key和$iv只能是16位,超过16位PHP加密失败,非16位,前端解密失败。如果加密方法是DES-ECB,则iv必须为空。
很多加密方法加密的结果是乱码,所以需要对结果进行base64编码,前端拿到直接解密,不需要base64解码。
PHP加密解密代码:
<?php
class Aes {
protected $method = 'AES-128-CBC';
protected $secret_key = 'Sd2@s.f9)_2o6dpu';
protected $options = OPENSSL_RAW_DATA;
public function encrypt($data) {
$ivlen = openssl_cipher_iv_length($this->method);
$iv = openssl_random_pseudo_bytes($ivlen);
$iv = bin2hex($iv);
if(strlen($iv) > $ivlen) {
$iv = substr($iv, 0, $ivlen);
}
if(is_array($data)) {
$data = json_encode($data);
}
$sign = openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $iv);
$sign = base64_encode($sign);
return array('sign' => $sign, 'iv' => $iv);
}
public function decrypt($sign, $iv) {
return openssl_decrypt($sign, $this->method, $this->secret_key, $this->options, $iv);
}
}
$aes = new Aes;
$content = array('name' => 'test', 'sex' => 'man');
$result = $aes->encrypt($content);
print_r($result);
$data = $aes->decrypt(base64_decode($result['sign']), $result['iv']);
print_r($data);
打印出加密结果是:
Array
(
[sign] => SeZA9+1qK1jsEiPlUC9Rlus8g91Kqm6V8aDV1au5y0Q=
[iv] => 8c30406e5d51d4bc
)
前端解密需要用到CryptoJS,下载地址https://github.com/sytelus/CryptoJS
前端解密代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="./CryptoJS-master/rollups/aes.js"></script>
<script src="./CryptoJS-master/components/mode-ecb.js"></script>
<script src="./CryptoJS-master/components/pad-nopadding.js"></script>
<script type="text/javascript">
var sign = "SeZA9+1qK1jsEiPlUC9Rlus8g91Kqm6V8aDV1au5y0Q=";
var iv = "8c30406e5d51d4bc";
iv = CryptoJS.enc.Utf8.parse(iv);
var key = "Sd2@s.f9)_2o6dpu";
key = CryptoJS.enc.Utf8.parse(key);
var decrypted = CryptoJS.AES.decrypt(sign, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding : CryptoJS.pad.Pkcs7
});
decrypted = decrypted.toString(CryptoJS.enc.Utf8);
console.log('decrypted', decrypted);
</script>
</head>
<body>
</body>
</html>