EncryptDecryptMiddleware.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace app\http\middleware;
  3. use Closure;
  4. use app\Request;
  5. use think\Response;
  6. class EncryptDecryptMiddleware
  7. {
  8. protected $secretKey = 'DUOs9QyBTDGdq3kPQcOnS6HEyp24He2h'; // 替换为你的密钥
  9. protected $cipher = 'AES-128-CBC';
  10. public function handle(Request $request, Closure $next): Response
  11. {
  12. // 解密请求数据
  13. if ($request->param('iv')) {
  14. $decryptedData = $this->decryptData($request->param('iv'));
  15. foreach ($decryptedData as $key => $value) {
  16. $request->param([$key => $value]);
  17. }
  18. // 继续执行下一个中间件或控制器
  19. $response = $next($request);
  20. // 加密响应数据
  21. $originalContent = $response->getContent();
  22. $encryptedContent = $this->encryptData(json_decode($originalContent, true));
  23. $response->setContent(json_encode($encryptedContent));
  24. return $response;
  25. } else {
  26. return $next($request);
  27. }
  28. }
  29. private function encryptData(array $data): array
  30. {
  31. $ivlen = openssl_cipher_iv_length($this->cipher);
  32. $iv = openssl_random_pseudo_bytes($ivlen);
  33. $ciphertext_raw = openssl_encrypt(json_encode($data), $this->cipher, $this->secretKey, OPENSSL_RAW_DATA, $iv);
  34. $hmac = hash_hmac('sha256', $ciphertext_raw, $this->secretKey, true);
  35. $ciphertext = base64_encode($iv . $hmac . $ciphertext_raw);
  36. return ['data' => $ciphertext];
  37. }
  38. private function decryptData(array $data): array
  39. {
  40. if (isset($data['data'])) {
  41. $c = base64_decode($data['data']);
  42. $ivlen = openssl_cipher_iv_length($this->cipher);
  43. $iv = substr($c, 0, $ivlen);
  44. $hmac = substr($c, $ivlen, $sha2len = 32);
  45. $ciphertext_raw = substr($c, $ivlen + $sha2len);
  46. $original_plaintext = openssl_decrypt($ciphertext_raw, $this->cipher, $this->secretKey, OPENSSL_RAW_DATA, $iv);
  47. $calcmac = hash_hmac('sha256', $ciphertext_raw, $this->secretKey, true);
  48. if (hash_equals($hmac, $calcmac)) {
  49. return json_decode($original_plaintext, true);
  50. }
  51. }
  52. return [];
  53. }
  54. }