60 lines
1.6 KiB
PHP
60 lines
1.6 KiB
PHP
<?php
|
|
// +----------------------------------------------------------------------
|
|
// | YwxApp [ WE CAN DO IT JUST THINK ]
|
|
// +----------------------------------------------------------------------
|
|
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
|
|
// +----------------------------------------------------------------------
|
|
// | Author: ywxapp<admin@ywxapp.cn>
|
|
// +----------------------------------------------------------------------
|
|
// server/utils/AesUtil.php
|
|
|
|
namespace ywxapp\utils;
|
|
|
|
/**
|
|
* AesUtil 类
|
|
*
|
|
* @author ywxapp <admin@ywxapp.cn>
|
|
*/
|
|
class AesUtil
|
|
{
|
|
private const METHOD = 'aes-256-cbc';
|
|
private static $key;
|
|
private static $iv;
|
|
|
|
|
|
public static function setKeyAndIv(string $key, string $iv)
|
|
{
|
|
if (strlen($key) !== 32) throw new \Exception("AES Key 必须为32字节");
|
|
if (strlen($iv) !== 16) throw new \Exception("AES IV 必须为16字节");
|
|
self::$key = $key;
|
|
self::$iv = $iv;
|
|
}
|
|
|
|
|
|
public static function encrypt(string $plaintext): string
|
|
{
|
|
$encrypted = openssl_encrypt(
|
|
$plaintext,
|
|
self::METHOD,
|
|
self::$key,
|
|
OPENSSL_RAW_DATA,
|
|
self::$iv
|
|
);
|
|
return base64_encode($encrypted);
|
|
}
|
|
|
|
|
|
public static function decrypt(string $ciphertext): string
|
|
{
|
|
$data = base64_decode($ciphertext);
|
|
$result = openssl_decrypt(
|
|
$data,
|
|
self::METHOD,
|
|
self::$key,
|
|
OPENSSL_RAW_DATA,
|
|
self::$iv
|
|
);
|
|
if ($result === false) throw new \Exception("AES 解密失败");
|
|
return $result;
|
|
}
|
|
} |