PHP code example of hlw2326 / think-request-crypto

1. Go to this page and download the library: Download hlw2326/think-request-crypto library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hlw2326 / think-request-crypto example snippets


return [
    // 是否启用加解密与签名验证
    'enabled'     => (bool) (env('CRYPTO_ENABLED', true)),

    // 签名密钥 (用于校验 X-Client-Sign 防篡改)
    'secret'      => (string) (env('CRYPTO_SIGN_SECRET') ?: env('CRYPTO_SECRET', '')),

    // 请求时钟最大容忍偏差秒数 (防重放攻击,默认 300 秒)
    'expire'      => (int) (env('CRYPTO_EXPIRE', 300)),

    // 服务端 RSA-2048 私钥 (用于解密 X-Client-Context 中的设备与 Token)
    'private_key' => (string) env('RSA_PRIVATE_KEY', ''),

    // 服务端 RSA-2048 公钥 (用于加密数据)
    'public_key'  => (string) env('RSA_PUBLIC_KEY', ''),
];

use Hlw\Crypto\Crypto;

// 1. 校验当前请求合法性并解密上下文
[$ok, $message, $context] = Crypto::verify($this->request);

if (!$ok) {
    return json(['code' => 0, 'msg' => $message], 401);
}

// 2. 获取客户端解密后的设备信息与登录 Token
$token = (string) ($this->request->header('token', '') ?: ($context['token'] ?? ''));

return [
    \Hlw\Crypto\middleware\CryptoMiddleware::class,
];