12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- <?php
- namespace app\http\middleware;
- use Closure;
- use app\Request;
- use think\Response;
- class EncryptDecryptMiddleware
- {
- protected $secretKey = 'DUOs9QyBTDGdq3kPQcOnS6HEyp24He2h'; // 替换为你的密钥
- protected $cipher = 'AES-128-CBC';
- public function handle(Request $request, Closure $next): Response
- {
- // 解密请求数据
- if ($request->param('iv')) {
- $decryptedData = $this->decryptData($request->param('iv'));
- foreach ($decryptedData as $key => $value) {
- $request->param([$key => $value]);
- }
- // 继续执行下一个中间件或控制器
- $response = $next($request);
- // 加密响应数据
- $originalContent = $response->getContent();
- $encryptedContent = $this->encryptData(json_decode($originalContent, true));
- $response->setContent(json_encode($encryptedContent));
- return $response;
- } else {
- return $next($request);
- }
- }
- private function encryptData(array $data): array
- {
- $ivlen = openssl_cipher_iv_length($this->cipher);
- $iv = openssl_random_pseudo_bytes($ivlen);
- $ciphertext_raw = openssl_encrypt(json_encode($data), $this->cipher, $this->secretKey, OPENSSL_RAW_DATA, $iv);
- $hmac = hash_hmac('sha256', $ciphertext_raw, $this->secretKey, true);
- $ciphertext = base64_encode($iv . $hmac . $ciphertext_raw);
- return ['data' => $ciphertext];
- }
- private function decryptData(array $data): array
- {
- if (isset($data['data'])) {
- $c = base64_decode($data['data']);
- $ivlen = openssl_cipher_iv_length($this->cipher);
- $iv = substr($c, 0, $ivlen);
- $hmac = substr($c, $ivlen, $sha2len = 32);
- $ciphertext_raw = substr($c, $ivlen + $sha2len);
- $original_plaintext = openssl_decrypt($ciphertext_raw, $this->cipher, $this->secretKey, OPENSSL_RAW_DATA, $iv);
- $calcmac = hash_hmac('sha256', $ciphertext_raw, $this->secretKey, true);
- if (hash_equals($hmac, $calcmac)) {
- return json_decode($original_plaintext, true);
- }
- }
- return [];
- }
- }
|