PHP Requires Chilkat v11.0.0+
Chilkat2 PHP
RSA Sign with PKCS8 Encrypted Key
See more RSA Examples
Demonstrates how to load a private key from an encrypted PKCS8 file and create an RSA digital signature (and then verify it).Chilkat PHP Downloads
<?php
use Chilkat2\Cert;
use Chilkat2\PrivateKey;
use Chilkat2\PublicKey;
use Chilkat2\Rsa;
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
$privKey = new PrivateKey();
// Load the private key from an RSA PEM file:
try {
$privKey->LoadAnyFormatFile('raul_privateKey.key', 'a0123456789');
$rsa = new Rsa();
// Import the private key into the RSA component:
$rsa->UsePrivateKey($privKey);
// This example will sign a string, and receive the signature
// in a hex-encoded string. Therefore, set the encoding mode
// to "hex":
$rsa->EncodingMode = 'hex';
$strData = 'This is the string to be signed.';
// Sign the string using the sha256 hash algorithm.
// Other valid choices are sha1, sha384, sha512 and others.
$hexSig = $rsa->SignStringENC($strData, 'sha256');
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
echo $hexSig, "\n";
// Now verify with the public key.
// This example shows how to use the public key from
// a digital certificate (.cer file)
$cert = new Cert();
try {
$cert->LoadFromFile('raul_publicKey.cer');
$pubKey = new PublicKey();
$cert->GetPublicKey($pubKey);
$rsa2 = new Rsa();
$rsa2->UsePublicKey($pubKey);
// Verify the signature against the original data:
$rsa2->EncodingMode = 'hex';
$rsa2->VerifyStringENC($strData, 'sha256', $hexSig);
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
echo "Signature verified!\n";
// Verify with incorrect data:
try {
$rsa2->VerifyStringENC('something else', 'sha256', $hexSig);
echo "Hmmm... that's not right...\n";
} catch (\Chilkat2\Exception $e) {
echo "Signature not verified! (which was expected in this case)\n";
}