Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.0.0+

RSA Hash Binary Data and Sign (and Verify)

See more RSA Examples

Demonstrates how to sign the hash of binary data. Also demonstrates how to verify the RSA signature.

Chilkat PHP Downloads

Chilkat2 PHP
<?php

use Chilkat2\BinData;
use Chilkat2\PrivateKey;
use Chilkat2\PublicKey;
use Chilkat2\Rsa;

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

// Load an RSA private key for signing.
$privKey = new PrivateKey();
try {
    $privKey->LoadEncryptedPemFile('qa_data/pem/rsa_passwd.pem', 'passwd');

    $rsa = new Rsa();
    $rsa->UsePrivateKey($privKey);

    // We have some binary data (in hex) to sign
    $originalData = '0102030405060708090A';
    $bdData = new BinData();
    $bdData->AppendEncoded($originalData, 'hex');

    // Hash (SHA-256) and sign the hash:
    $bdSignature = new BinData();
    $rsa->SignBd($bdData, 'sha256', $bdSignature);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Show the RSA signature in base64
echo $bdSignature->GetEncoded('base64'), "\n";

// ------------------------------------------
// Get the public key from the private key
$pubKey = new PublicKey();
$privKey->ToPublicKey($pubKey);

// Verify the signature..
$rsa2 = new Rsa();
$rsa2->UsePublicKey($pubKey);

try {
    $rsa2->VerifyBd($bdData, 'sha256', $bdSignature);
    $bVerified = true;
} catch (\Chilkat2\Exception $e) {
    $bVerified = false;
}
echo 'signature verified: ', ($bVerified ? 'true' : 'false'), "\n";