PHP
PHP
Get Public Key from CSR
See more CSR Examples
Demonstrates how to get the public key from a CSR.Chilkat PHP Downloads
<?php
use Chilkat2\Asn;
use Chilkat2\BinData;
use Chilkat2\Pem;
use Chilkat2\PublicKey;
use Chilkat2\Xml;
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
$pem = new Pem();
// No password is required. Pass an empty password string..
$noPassword = '';
try {
$pem->LoadPemFile('qa_data/csr/csr2.pem', $noPassword);
$strBase64 = $pem->GetEncodedItem('csr', '', 'base64', 0);
$asn = new Asn();
$asn->LoadEncoded($strBase64, 'base64');
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
// Convert the ASN.1 to XML.
$xml = new Xml();
$xml->LoadXml($asn->AsnToXml());
echo $xml->GetXml(), "\n";
echo "----\n";
$strModulusHex = $xml->GetChildContent('bits');
echo 'strModulusHex = ', $strModulusHex, "\n";
echo "----\n";
// We need the modulus as base64.
$bd = new BinData();
$bd->AppendEncoded($strModulusHex, 'hex');
$modulus64 = $bd->GetEncoded('base64');
echo 'modulus64 = ', $modulus64, "\n";
echo "----\n";
// Build the XML for the public key.
$xmlPubKey = new Xml();
$xmlPubKey->Tag = 'RSAPublicKey';
$xmlPubKey->UpdateChildContent('Modulus', $modulus64);
// The RSA exponent will always be decimal 65537 (base64 = AQAB)
$xmlPubKey->UpdateChildContent('Exponent', 'AQAB');
echo "RSA public key as XML:\n";
echo $xmlPubKey->GetXml(), "\n";
echo "----\n";
// Load the XML into a Chilkat public key object.
$pubkey = new PublicKey();
try {
$pubkey->LoadFromString($xmlPubKey->GetXml());
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
// Show the public key as PEM.
$preferPkcs1 = true;
echo $pubkey->GetPem($preferPkcs1), "\n";