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 []; } }