PHP Signature & Verification Example
In API requests, to ensure data integrity and security, we use the RSA signature mechanism to encrypt and sign requests, and verify signatures on the receiving end.
This example provides a SignatureHandler class for generating signatures and verifying signatures
php
<?php
namespace Sign;
class SignatureHandler
{
private $key;
private $is_private;
public function __construct(string $key, string $key_type = 'private')
{
// Initialize signature/verification class
if ($key_type == 'private') {
// Generate private key
$pem_key = "-----BEGIN PRIVATE KEY-----\n" . wordwrap($key, 64, "\n", true) . "\n-----END PRIVATE KEY-----";
$this->key = openssl_pkey_get_private($pem_key);
$this->is_private = true;
} elseif ($key_type == 'public') {
// Generate public key
$pem_key = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($key, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
$this->key = openssl_pkey_get_public($pem_key);
$this->is_private = false;
} else {
throw new Exception("Invalid key_type. Must be 'private' or 'public'.");
}
}
public function generate_signature(string $merchant_id, string $timestamp, string $timezone, array $body): string
{
if (!$this->is_private) {
throw new Exception("Key must be private to generate signature.");
}
// Assemble signature content
$body_str = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$sign_content = "$merchant_id.$timestamp.$timezone.$body_str";
// Generate signature
$signature = null;
openssl_sign($sign_content, $signature, $this->key, OPENSSL_ALGO_SHA256);
// Return Base64 encoded signature string
return base64_encode($signature);
}
public function verify_signature(string $merchant_id, string $timestamp, string $timezone, array $body, string $received_signature): bool
{
if ($this->is_private) {
throw new Exception("Key must be public to verify signature.");
}
// Assemble signature content
$body_str = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$sign_content = "$merchant_id.$timestamp.$timezone.$body_str";
// Decode received signature
$decoded_signature = base64_decode($received_signature);
// Verify signature
$result = openssl_verify($sign_content, $decoded_signature, $this->key, OPENSSL_ALGO_SHA256);
// Return true if verification succeeds, false otherwise
return $result === 1;
}
}