使用openssl_encrypt/openssl_decrypt方式加解密(需要PHP版本7+)。
加解密类:
class Crypt {
/**
* 加密字符串
* @param string $string 要加密的字符串
* @param string $key 加密私钥
* @return array
*/ public function encrypt($string, $key) {
$ivlen = openssl_cipher_iv_length('AES-256-CBC');
$iv = openssl_random_pseudo_bytes($ivlen);
$encrypted = openssl_encrypt($string, 'AES-256-CBC', $key, $options = OPENSSL_RAW_DATA, $iv);
$data = [
'hash' => hash_hmac('sha256', $encrypted, $key),
'data' => base64_encode($iv . $encrypted),
];
return $data;
}
/**
* 解密字符串
* @param string $string 要解密的字符串
* @param string $key 私钥
* @param string $hash 校验hash
* @return string
*/ public function decrypt($string, $key, $hash) {
$data = base64_decode($string);
$ivlen = openssl_cipher_iv_length('AES-256-CBC');
$iv = substr($data, 0, $ivlen);
$data = substr($data, $ivlen);
$decrypted = openssl_decrypt($data, 'AES-256-CBC', $key, $options = OPENSSL_RAW_DATA, $iv);
$hash = hash_hmac('sha256', $data, $key);
if ($hash !== $hash) {
return false;
}
return $decrypted;
}
}
测试内容:
$crypt = new Crypt;
$key = '20190523';
$string = json_encode(['Hello' => 'World']);
$encrypted = $crypt->encrypt($string, $key);
var_dump($encrypted); echo "<br>";
$decrypted = $crypt->decrypt($encrypted['data'], $key, $encrypted['hash']);
var_dump($decrypted);