zfegg/http-content-crypt

PSR7 中间件的 HTTP 内容加密/签名

0.2.1 2017-02-07 02:24 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:14:52 UTC


README

PSR7 中间件的 HTTP 内容加密/签名

安装

通过 composer 安装

# composer require zfegg/http-content-crypt

用法

ContentCryptMiddleware

使用 RSA+AES 进行内容加密。

HTTP 流

POST /action HTTP/1.1
Host: localhost
Content-Type: application/json
Accept: application/json
X-Content-Encoding: rsaaes, base64
X-Crypto-Key: keyid=1; data=`Urlencode(BASE64.encode(RSA.encode(AesKey)))`

`BASE64.encode(AES.encode('{"test":"test content"}'));`

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: n
X-Content-Encoding: rsaaes, base64

`BASE64.decode(AES.decode('{"test":"test response content"}'));`

Slim 示例

use Psr\Http\Message\ServerRequestInterface;

$app = new \Slim\App($settings);

$container = $app->getContainer();
$container[ContentCryptMiddleware::class] = function () {
    $middleware = new ContentCryptMiddleware();

    $rsa = Rsa::factory([
        'public_key' => '',
        'private_key' => '',
        'binary_output' => false,
    ]);

    $middleware->setFetchRsaCallback(function ($keyId, ServerRequestInterface $request) use ($rsa) {
        return $rsa;
    });
    return $middleware;
};

$app->post('/test', function (\Psr\Http\Message\ServerRequestInterface $request, \Slim\Http\Response $response) {
    $rawBody = $request->getBody();
    return $request->write($rawBody);
})->add(ContentCryptMiddleware::class);

$app->run();

ContentSignatureMiddleware

使用 HMAC 哈希验证内容签名。

POST, PUT, PATCH 请求中,对 HTTP 内容进行 HMAC-HASH 方式签名计算。

内容签名主要用于验证传输内容的合法性,防止接口泄露和恶意使用。

HTTP 流

POST /action HTTP/1.1
Host: localhost
Content-Type: application/json
Accept: application/json
Content-Signature: keyid=1; value=(hash_hex); alg=(md5|sha1|...);

payload

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: n
Content-Signature: keyid=1; value=(hash_hex); alg=(md5|sha1|...);

payload

Slim 示例

use Psr\Http\Message\ServerRequestInterface;

$app = new \Slim\App($settings);

$container = $app->getContainer();
$container[ContentSignatureMiddleware::class] = function () {
    $middleware = new ContentSignatureMiddleware();
    $middleware->setFetchRsaCallback(function ($keyId, ServerRequestInterface $request) {
        return "123456";
    });
    return $middleware;
};

$app->post('/test', function (ServerRequestInterface $request, $response) {
    $rawBody = $request->getBody();
    return $request->write($rawBody);
})->add(ContentSignatureMiddleware::class);

$app->run();