// +---------------------------------------------------------------------- // server/utils/AesUtil.php namespace ywxapp\utils; /** * AesUtil 类 * * @author ywxapp */ 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; } }