PHP code implements request parameter encryption and decryption processing of Baidu Wenxin Yiyan API interface
Hitokoto is a service that provides access to random sentences, Baidu Wenxinyiyan API is one of the interfaces that developers can call. In order to ensure data security, we can encrypt the request parameters and decrypt the response after receiving the response. The following is an example of PHP code implementing the request parameter encryption and decryption processing of Baidu Wenxin Yiyan API interface:
<?php function encryptData($data, $key) { $method = 'AES-128-ECB'; // 加密方法 $iv = ""; // 初始化向量 $encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv); $encrypted = base64_encode($encrypted); return $encrypted; } function decryptData($data, $key) { $method = 'AES-128-ECB'; // 解密方法 $iv = ""; // 初始化向量 $decrypted = openssl_decrypt(base64_decode($data), $method, $key, OPENSSL_RAW_DATA, $iv); return $decrypted; } // 请求参数加密处理示例 $url = "http://api.hitokoto.cn/"; // API接口地址 $key = "your_encryption_key"; // 加密密钥 $params = [ "c" => "category", "s" => "source", ]; // 请求参数 $encryptedParams = encryptData(json_encode($params), $key); // 加密参数 $encryptedParams = urlencode($encryptedParams); // 对加密结果进行URL编码 $requestUrl = $url . "?params=" . $encryptedParams; // 发起API请求 $response = file_get_contents($requestUrl); // 解密响应数据示例 $encryptedResponse = $_GET['response']; // 获取加密后的响应数据 $decryptedResponse = decryptData($encryptedResponse, $key); // 解密响应数据 $decodedResponse = json_decode($decryptedResponse, true); // 将解密结果转换为数组或对象 // 输出结果 var_dump($decodedResponse); ?>
In the above code, the encryptData
function is used to encrypt the request parameters. , decryptData
function is used to decrypt response data. During the encryption and decryption process, we use the AES-128-ECB encryption algorithm and need to provide the encryption key. For encrypted parameters, they need to be URL encoded and sent as request parameters.
When actually calling, you need to set $url
in the code to the actual API interface address, and $key
to the secure key. $params
is the request parameters you want to send, which can be modified accordingly according to the interface document. Afterwards, you can process and use the decrypted response data accordingly according to actual needs.
Hope this sample code can help you encrypt and decrypt the request parameters of Baidu Wenxin Yiyan API interface to ensure data security. Of course, in actual projects, you may also need to consider other security factors and perform appropriate optimization and packaging.
The above is the detailed content of PHP code implements request parameter encryption and decryption processing of Baidu Wenxinyiyan API interface. For more information, please follow other related articles on the PHP Chinese website!