PHPackages                             hejunjie/encrypted-request - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. hejunjie/encrypted-request

ActiveLibrary[Security](/categories/security)

hejunjie/encrypted-request
==========================

PHP 请求加密工具包，支持 AES 解密、签名与时间戳验证，快速实现前后端安全通信 | PHP encryption toolkit for AES decryption, signature, and timestamp verification, enabling fast and secure front-to-backend communication. Front-end npm package generates encrypted request parameters without changing existing APIs

v3.0.0(1mo ago)2260↓90%1MITPHPPHP ^8.0

Since Aug 26Pushed 1mo agoCompare

[ Source](https://github.com/zxc7563598/php-encrypted-request)[ Packagist](https://packagist.org/packages/hejunjie/encrypted-request)[ RSS](/packages/hejunjie-encrypted-request/feed)WikiDiscussions main Synced 2w ago

READMEChangelog (4)Dependencies (3)Versions (5)Used By (0)

hejunjie/encrypted-request
==========================

[](#hejunjieencrypted-request)

English ｜ [简体中文](./README.zh-CN.md)

A PHP encryption toolkit for secure front-end to back-end communication.

In real-world development, API endpoints often require security: data needs encryption to prevent sniffing, and requests must be protected from tampering and replay attacks. Coordinating encryption methods and signature rules with the front-end can be tedious. This package, paired with the [front-end npm package](https://github.com/zxc7563598/npm-encrypted-request), lets the front-end generate encrypted request parameters with a single call, while the back-end decrypts and verifies in just a few lines of code.

Front-end companion npm package: [npm-encrypted-request](https://github.com/zxc7563598/npm-encrypted-request)

**This project has been parsed by Zread. Click to learn more: [Learn More](https://zread.ai/zxc7563598/php-encrypted-request)**

Features
--------

[](#features)

- 🔐 **Hybrid encryption**: AES-256-GCM symmetric encryption + RSA-OAEP asymmetric encryption. AES keys are randomly generated by the front-end and transmitted via RSA public key encryption — the back-end only needs the RSA private key
- ✍️ **HMAC-SHA256 signature verification**: Prevents request parameters from being tampered with
- ⏰ **Timestamp validation**: Second-level verification with configurable tolerance to prevent request replay
- 🔑 **Nonce anti-replay**: One-time random number mechanism to block duplicate requests
- ⚙️ **Flexible configuration**: Supports `.env` files, inline arrays, or custom `.env` paths
- 🧩 **Extensible**: Pluggable Nonce validator (Redis, APCu, etc.) for production environments

Installation
------------

[](#installation)

```
composer require hejunjie/encrypted-request
```

Quick Start
-----------

[](#quick-start)

### 1. Configuration

[](#1-configuration)

Via `.env` file:

```
RSA_PRIVATE_KEY=your-private-key
SIGN_SECRET=your-sign-secret
DEFAULT_TIMESTAMP_DIFF=60
NONCE_TTL=300
```

Or via an array:

```
$config = [
    'RSA_PRIVATE_KEY'       => 'your-private-key',   // RSA private key (including -----BEGIN PRIVATE KEY-----)
    'SIGN_SECRET'            => 'your-sign-secret',   // HMAC-SHA256 signing key
    'DEFAULT_TIMESTAMP_DIFF' => 60,                   // Timestamp tolerance in seconds, default 60
    'NONCE_TTL'              => 300,                  // Nonce TTL in seconds, default 300
];
```

### 2. Decrypt Requests

[](#2-decrypt-requests)

```
use Hejunjie\EncryptedRequest\EncryptedRequestHandler;
use Hejunjie\EncryptedRequest\Contracts\NonceValidatorInterface;

$params = $_POST; // Obtain front-end request parameters

// EncryptedRequestHandler constructor:
//   __construct(array|string $config = '', int $protocolVersion = 1, ?NonceValidatorInterface $nonceValidator = null)
//
// - First argument: config array, .env file path, or omit (auto-detect .env)
// - Second argument: Protocol version — defaults to 1
// - Third argument: Nonce validator — defaults to in-memory implementation (testing only!)

$handler = new EncryptedRequestHandler($config);  // Omit first argument if using .env

try {
    $data = $handler->handle(
        $params['en_data'] ?? '',
        $params['enc_payload'] ?? '',
        (int)($params['timestamp'] ?? 0),
        $params['sign'] ?? ''
    );
    // $data is the decrypted array
} catch (\Hejunjie\EncryptedRequest\Exceptions\SignatureException $e) {
    // Invalid signature
} catch (\Hejunjie\EncryptedRequest\Exceptions\TimestampException $e) {
    // Timestamp out of range
} catch (\Hejunjie\EncryptedRequest\Exceptions\NonceException $e) {
    // Nonce already used (replay attack)
} catch (\Hejunjie\EncryptedRequest\Exceptions\DecryptionException $e) {
    // RSA or AES decryption failed
}
```

Warning

Without the third argument, the default `InMemoryNonceValidator` stores nonces in process memory, which is **lost after each PHP request** — it cannot truly prevent replay attacks. **Always pass a custom Nonce validator in production.** See the "Custom Nonce Validator" section below.

Configuration Reference
-----------------------

[](#configuration-reference)

ConfigTypeRequiredDefaultDescription`RSA_PRIVATE_KEY`string✅-RSA private key for decrypting the AES key from the front-end`SIGN_SECRET`string✅-HMAC-SHA256 signing key, must match the front-end`DEFAULT_TIMESTAMP_DIFF`int❌`60`Timestamp tolerance in seconds`NONCE_TTL`int❌`300`Nonce time-to-live in secondsHow It Works
------------

[](#how-it-works)

```
Signature Verification → Timestamp Check → RSA Decrypt (AES Key) → Nonce Anti-Replay → AES-256-GCM Decrypt

```

1. **Signature verification** (runs first): HMAC-SHA256 over `en_data + enc_payload + timestamp` using `SIGN_SECRET`. Invalid requests are rejected immediately.
2. **Timestamp check**: Ensures the request timestamp is within the configured tolerance.
3. **RSA decryption**: Decrypts `enc_payload` with the RSA private key to obtain the AES key, IV, and Nonce.
4. **Nonce verification**: Checks whether the Nonce has been used before, preventing replay attacks.
5. **AES-256-GCM decryption**: Decrypts the request data using the extracted AES key and IV.

Front-End Integration
---------------------

[](#front-end-integration)

The front-end uses the [hejunjie-encrypted-request](https://github.com/zxc7563598/npm-encrypted-request) npm package to generate encrypted data:

```
import { encryptRequest, EncryptOptions } from "hejunjie-encrypted-request";

const options: EncryptOptions = {
    data: { message: "Hello" },
    rsaPublicKey: pubKey,
    signSecret: signSecret,
};

const payload = await encryptRequest(options, version);
```

The PHP back-end can then decrypt directly using `EncryptedRequestHandler`.

Custom Nonce Validator
----------------------

[](#custom-nonce-validator)

The default `InMemoryNonceValidator` stores nonces in process memory and is **only suitable for single-process or testing environments**. For production, implement the `NonceValidatorInterface` (e.g., with Redis, APCu, or a database) and pass it as the **third argument** to the `EncryptedRequestHandler` constructor:

```
use Hejunjie\EncryptedRequest\EncryptedRequestHandler;
use Hejunjie\EncryptedRequest\Contracts\NonceValidatorInterface;

// 1. Implement NonceValidatorInterface
class RedisNonceValidator implements NonceValidatorInterface
{
    private \Redis $redis;

    public function __construct(\Redis $redis)
    {
        $this->redis = $redis;
    }

    public function verify(string $nonce, int $ttl): bool
    {
        // Use SET NX EX for atomic check-and-set
        return $this->redis->set("nonce:{$nonce}", 1, ['nx', 'ex' => $ttl]) === true;
    }
}

// 2. Inject as the third argument (using named parameter)
$handler = new EncryptedRequestHandler(
    $config,                                    // First argument: config
    nonceValidator: new RedisNonceValidator($redis)  // Third argument: custom Nonce validator
);
```

Directory Structure
-------------------

[](#directory-structure)

```
src/
├── Config/
│   └── EnvConfigLoader.php          # Configuration loader (.env + array)
├── Contracts/
│   ├── DecryptorInterface.php       # Decryptor interface
│   └── NonceValidatorInterface.php  # Nonce validator interface
├── Drivers/
│   ├── AesDecryptor.php             # AES-256-GCM decryptor
│   ├── InMemoryNonceValidator.php   # In-memory Nonce validator (default, testing only)
│   └── RsaDecryptor.php             # RSA-OAEP decryptor
├── Exceptions/
│   ├── DecryptionException.php      # Decryption exception
│   ├── NonceException.php           # Nonce exception (replay attack)
│   ├── SignatureException.php       # Signature exception
│   └── TimestampException.php       # Timestamp exception
└── EncryptedRequestHandler.php      # Core handler

```

Compatibility
-------------

[](#compatibility)

- PHP &gt;= 8.0
- Requires PHP OpenSSL extension
- Works with any PSR-4 autoloading framework or vanilla PHP project

FAQ
---

[](#faq)

### Is the default Nonce validator suitable for production?

[](#is-the-default-nonce-validator-suitable-for-production)

No. `InMemoryNonceValidator` stores data in process memory, which is lost after each PHP request — it cannot reliably prevent replay attacks. For production, inject a Redis or database-backed implementation as shown in the "Custom Nonce Validator" section above.

### How do I keep the signing key consistent between front-end and back-end?

[](#how-do-i-keep-the-signing-key-consistent-between-front-end-and-back-end)

The `SIGN_SECRET` value must exactly match the `signSecret` parameter passed to `encryptRequest()` on the front-end. Store the key in `.env` and sync it to the front-end through a secure channel.

### Which PHP frameworks are supported?

[](#which-php-frameworks-are-supported)

Any project following PSR-4 autoloading, including but not limited to Laravel, Symfony, Slim, ThinkPHP, and plain PHP projects.

Contributing
------------

[](#contributing)

Issues and pull requests are welcome.

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance93

Actively maintained with recent releases

Popularity18

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~107 days

Total

4

Last Release

36d ago

Major Versions

v0.0.1 → v1.0.02025-08-26

v1.0.0 → v2.0.02025-08-28

v2.0.0 → v3.0.02026-07-14

### Community

Maintainers

![](https://www.gravatar.com/avatar/5b65d4b40ae456172fb38f63f84bf737ac88031484b1f228b1cc8d71baa80adf?d=identicon)[苏青安](/maintainers/%E8%8B%8F%E9%9D%92%E5%AE%89)

---

Top Contributors

[![zxc7563598](https://avatars.githubusercontent.com/u/46590942?v=4)](https://github.com/zxc7563598 "zxc7563598 (13 commits)")

---

Tags

aes-encryptionencrypted-requestfrontend-integrationphpphp-packagerequest-signaturessecure-apisecuritytimestamp-validation

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/hejunjie-encrypted-request/health.svg)

```
[![Health](https://phpackages.com/badges/hejunjie-encrypted-request/health.svg)](https://phpackages.com/packages/hejunjie-encrypted-request)
```

###  Alternatives

[laravel/framework

The Laravel Framework.

34.9k556.2M21.5k](/packages/laravel-framework)[tempest/framework

The PHP framework that gets out of your way.

2.3k37.6k21](/packages/tempest-framework)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45844.8k1](/packages/pressbooks-pressbooks)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

265.2k](/packages/aedart-athenaeum)[lion/bundle

Lion-framework configuration and initialization package

132.4k5](/packages/lion-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
