Search by

wenber-yu / req-res-crypto-core

wenber-yu

PHP request-response encryption core: Ed25519 signing, X25519 key exchange, XChaCha20-Poly1305 AEAD encryption. Zero framework dependencies.

Package info

github.com/wenber-yu/req-res-crypto-core

pkg:composer/wenber-yu/req-res-crypto-core

Statistics

Installs: 2

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

0.1.2 2026-11-26 18:39 UTC

This package is auto-updated.

Last update: 2026-11-27 10:38:25 UTC


README

PHP 请求 / 响应加密核心库,零框架依赖。基于 AEAD 加密(XChaCha20-Poly1305)+ X25519 ECDH 密钥交换。

密码方案

层次 算法 用途
密钥协商 X25519 ECDH 客户端与服务端协商共享密钥
加密 XChaCha20-Poly1305 IETF AEAD 加解密请求/响应体

AEAD 内建的 Poly1305 MAC 提供数据认证,无需额外的 Ed25519 签名。

Wire Format

v2(兼容模式,请求和响应共用)

┌─────────┬───────────────────┬───────────┬───────────────────────┐
│ version │ exchange_pubkey   │ timestamp │ nonce(24) + ciphertext│
│  1 byte │     32 bytes      │  8 bytes  │        变长            │
└─────────┴───────────────────┴───────────┴───────────────────────┘
  • version: 固定 0x02
  • exchange_pubkey: 己方 X25519 公钥,直接嵌入 wire
  • timestamp: Unix 时间戳(小端序),防重放时间窗口校验
  • body: nonce(24) || ciphertext,XChaCha20-Poly1305 IETF AEAD

最小有效长度:1 + 32 + 8 + 24 + 1 = 66 字节。

AAD:前 41 字节 header(version || exchange_pubkey || timestamp)作为 AEAD 附加认证数据。 任何对 header 的篡改都会导致解密失败,因此时间戳与公钥无法被无痕改写。

v3(会话模式,双向会话级前向保密)

请求:

version(3) | session_id(16) | client_eph_pub(32) | timestamp(8) | nonce(24) | ciphertext

响应:

version(3) | session_id(16) | timestamp(8) | nonce(24) | ciphertext
  • 先调用 GET /req-res-crypto/handshake 获取带 Ed25519 签名的服务端临时 X25519 公钥
  • shared = X25519(临时私钥, 对方临时公钥)
  • 请求密钥:BLAKE2b-256(shared || "req-res-crypto:v3:request" || header)
  • 响应密钥:BLAKE2b-256(shared || "req-res-crypto:v3:response" || header)
  • 服务端只在 SessionStoreInterface 中按 session_id 保存临时私钥,TTL 到期删除;静态密钥不参与会话加解密
  • Unsealer 同时接受 v2 / v3,v2 请求仍由静态交换密钥处理

安装

composer require wenber-yu/req-res-crypto-core

依赖:PHP >= 8.3,ext-sodium。

核心 API

Sealer(加密器)

use Wenbo\ReqResCrypto\Core\Sealer;
use Wenbo\ReqResCrypto\Core\KeyExchange;
use Wenbo\ReqResCrypto\Core\JsonSerializer;

$sealer = new Sealer(
    new KeyExchange(),
    new JsonSerializer(),
);

$wire = $sealer->seal(
    exchangePublicKey: bin2hex($myExchangePubKey),   // 己方 X25519 公钥(hex)
    exchangeSecretKey: $myExchangeSecretKey,          // 己方 X25519 私钥
    theirExchangePubKey: $theirExchangePubKey,       // 对方 X25519 公钥
    plaintext: ['action' => 'query', 'id' => 42],
);

// $wire 为二进制 wire format,传输前应 base64 编码
$payload = base64_encode($wire);

Unsealer(解密器)

use Wenbo\ReqResCrypto\Core\Unsealer;
use Wenbo\ReqResCrypto\Core\KeyExchange;
use Wenbo\ReqResCrypto\Core\JsonSerializer;

$unsealer = new Unsealer(
    keyExchange: new KeyExchange(),
    keyProvider: $keyProvider,       // 实现 ServerKeyProviderInterface
    nonceStore: $nonceStore,         // 实现 NonceStoreInterface
    serializer: new JsonSerializer(),
    timeWindow: 300,                 // 时间容差(秒),默认 300
    nonceTtl: 600,                   // nonce 去重记录保留时间(秒),默认 600
);

/** @var \Wenbo\ReqResCrypto\Core\Unsealed $unsealed */
$unsealed = $unsealer->unseal(base64_decode($wire));

$data = $unsealed->data;

// 客户端 X25519 公钥(用于加密响应)随返回值交出,Unsealer 不保存任何请求态
$clientPubKey = $unsealed->clientExchangePublicKey;

// v3 会话请求会额外返回 session_id(二进制 16 字节),响应方据此走会话加密
if ($unsealed->session) {
    $sessionId = $unsealed->sessionId;
}

Unsealer 是无状态的,可安全地在多个协程/请求间共享同一个实例。

解密流程:

  1. 解析 version(2 / 3)
  2. v2:取静态交换私钥做 ECDH;v3:按 session_id 从 SessionStore 取临时私钥做 ECDH
  3. XChaCha20-Poly1305 解密(header 作为 AAD 参与认证)
  4. 时间窗口校验(默认 ±300 秒)
  5. Nonce 去重(解密成功后才写入,避免垃圾请求占存储)
  6. JSON 反序列化

会话握手(v3 前向保密)

use Wenbo\ReqResCrypto\Core\HandshakeService;
use Wenbo\ReqResCrypto\Core\SessionSealer;
use Wenbo\ReqResCrypto\Core\KeyDerivation;
use Wenbo\ReqResCrypto\Core\JsonSerializer;

// 实现 SessionStoreInterface(缓存/Redis),保存 session_id -> 服务端临时私钥
$handshakeService = new HandshakeService($keyProvider, $sessionStore);

$handshake = $handshakeService->issue(600); // 会话有效期 600 秒
$json = $handshake->toArray();              // 直接作为握手接口响应

$sessionSealer = new SessionSealer(new KeyDerivation(), new JsonSerializer());
$responseWire = $sessionSealer->sealResponse(
    $sessionStore->get($unsealed->sessionId),
    $unsealed->clientExchangePublicKey,
    $unsealed->sessionId,
    ['ok' => true],
);

HandshakePayload 定义了握手响应的待签字节(sig_version = 3),与 JS 端 buildHandshakePayload() 逐字节一致。

KeyPair(密钥对生成)

use Wenbo\ReqResCrypto\Core\KeyPair;

$keyPair = KeyPair::generate();

// 属性(均为 32 字节二进制)
$keyPair->signPublicKey;      // Ed25519 签名公钥
$keyPair->signSecretKey;      // Ed25519 签名私钥
$keyPair->exchangePublicKey;  // X25519 交换公钥
$keyPair->exchangeSecretKey;  // X25519 交换私钥
$keyPair->keyId();            // 前 4 字节 hex,用作 Key ID

ServerKeyProviderInterface(服务端密钥管理)

interface ServerKeyProviderInterface
{
    public function getCurrentKeyId(): ?string;
    public function getSignSecretKey(string $keyId): ?string;
    public function getExchangeSecretKey(string $keyId): ?string;
    public function getSignPublicKey(string $keyId): ?string;
    public function getExchangePublicKey(string $keyId): ?string;
    public function getPreIssuedKeyId(): ?string;
}

JsonSerializer(JSON 序列化器)

实现 SerializerInterface,统一请求/响应的 JSON 编解码:

use Wenbo\ReqResCrypto\Core\JsonSerializer;

$serializer = new JsonSerializer();
$json = $serializer->serialize(['key' => 'value']);       // → JSON 字符串
$data = $serializer->unserialize('{"key":"value"}');       // → 关联数组

默认使用 JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES 编码,unserialize 前会 json_validate 校验。

ServerKey(服务端密钥值对象)

ServerKeyProviderInterface::getCurrentKey() 的返回类型,封装一对服务端密钥:

final readonly class ServerKey
{
    public string $keyId;             // 8 字符 hex
    public string $signSecretKey;     // Ed25519 签名私钥(二进制,用于签发公钥响应)
    public string $signPublicKey;     // Ed25519 签名公钥(二进制,下发给客户端验签)
    public string $exchangeSecretKey; // X25519 交换私钥(二进制)
    public string $exchangePublicKey; // X25519 交换公钥(二进制)
}

sign_* 字段用于公钥下发响应签名:服务端用 signSecretKey 签发 ServerKeysPayload,客户端用 signPublicKey 验签。业务报文本身不额外签名, 由 AEAD 的 Poly1305 MAC 认证。

边界:Ed25519 无法建立首次信任。首次要么依赖 HTTPS + TOFU,要么在前端内置 根公钥(rootSignPublicKey);服务端被攻破、客户端被 XSS 篡改本地存储均不在防护范围内。

PathMatcher(路径模式匹配)

支持 *(单段)和 **(递归多段)通配符的路径匹配工具:

use Wenbo\ReqResCrypto\Core\PathMatcher;

PathMatcher::matches('/api/users/123', '/api/**');   // true
PathMatcher::matches('/api/v2', '/api/*');           // true
PathMatcher::matches('/api/v2/list', '/api/*');      // false(跨段)
PathMatcher::matches('/api/publicity/list', '/api/public/**'); // false(严格边界)

PathMatcher::matchesAny('/health', ['/api/**', '/health']); // true

** 不会匹配父路径本身:/api/public/** 不匹配 /api/public, 如需同时放行父路径请配置 /api/public 与 /api/public/** 两条。

框架适配包用此工具实现 skip_routes 配置。

NonceStoreInterface(防重放)

interface NonceStoreInterface
{
    public function exists(string $nonce): bool;

    /**
     * 原子写入 nonce,返回是否首次存储。
     * 高并发下必须用"不存在则写入"的原子操作(如 Cache::add、Redis SET NX),
     * 避免 check-then-store 竞态导致重放攻击绕过。
     *
     * @return bool true = 首次存储成功,false = nonce 已存在(重复)
     */
    public function store(string $nonce, int $ttlSeconds): bool;
}

异常体系

异常 父类 说明
CryptoException RuntimeException 加解密失败、消息格式错误等
KeyException CryptoException 密钥未找到、密钥无效
ReplayException CryptoException 重放检测(过期/未来时间戳、重复 Nonce)

密钥轮换

核心包仅定义 ServerKeyProviderInterface,完整的密钥轮换(数据库持久化、定时 Crontab、Artisan 命令)由框架适配包提供:

框架适配

框架 包 功能
Hyperf req-res-crypto-hyperf PSR-15 中间件、数据库密钥轮换、Crontab、Command 命令
Laravel req-res-crypto-laravel 中间件、Facade、注解驱动加解密、数据库密钥轮换、Artisan 命令

前端对接

前端(浏览器)客户端 req-res-crypto-js,提供 axios / fetch 透明加解密集成。客户端每次请求动态生成 X25519 密钥对(~0.05ms),公钥嵌入 wire,用完即弃。

npm install @wenber-yu/req-res-crypto-js