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