shop-php/extend/AES.php

44 lines
1.1 KiB
PHP

<?php
class AES
{
public $cipher = 'aes-128-cbc';
/**
* 使用对称密钥进行加密
* @param $plainText
* @param $secret
* @param $iv
* @return string
*/
function encrypt($plainText, $secret, $iv = null)
{
$plainText = json_encode($plainText);
if (!empty($iv)) {
$encryptedData = openssl_encrypt($plainText, $this->cipher, $secret, OPENSSL_RAW_DATA, $iv);
} else {
$encryptedData = openssl_encrypt($plainText, $this->cipher, $secret);
}
return base64_encode($encryptedData);
}
/**
* 使用对称秘钥解密
* @param $plainText
* @param $secret
* @param $iv
* @return false|string
*/
function decrypt($plainText, $secret, $iv = null) {
$plainText = base64_decode($plainText);
if (!empty($iv)) {
$data = openssl_decrypt($plainText, $this->cipher, $secret, OPENSSL_RAW_DATA, $iv);
$data = json_decode($data, true);
return $data;
}
return openssl_decrypt($plainText, $this->cipher, $secret);
}
}