PHP code example of hejunjie / encrypted-request

1. Go to this page and download the library: Download hejunjie/encrypted-request 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/ */

    

hejunjie / encrypted-request example snippets


$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
];

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
}

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
);

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