Sample code for 30+ languages & platforms
Perl

Get Public Key from CSR

See more CSR Examples

Demonstrates how to get the public key from a CSR.

Chilkat Perl Downloads

Perl
use strict;
use warnings;
use Chilkat2;

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

my $pem = Chilkat2::Pem->new;

# No password is required.  Pass an empty password string..
my $noPassword = '';
my $success = $pem->LoadPemFile('qa_data/csr/csr2.pem', $noPassword);
if (!$success) {
    print $pem->LastErrorText, "\n";
    exit;
}

my $strBase64 = $pem->GetEncodedItem('csr', '', 'base64', 0);

my $asn = Chilkat2::Asn->new;
$success = $asn->LoadEncoded($strBase64, 'base64');
if (!$success) {
    print $asn->LastErrorText, "\n";
    exit;
}

# Convert the ASN.1 to XML.
my $xml = Chilkat2::Xml->new;
$success = $xml->LoadXml($asn->AsnToXml());
print $xml->GetXml(), "\n";
print "----\n";

my $strModulusHex = $xml->GetChildContent('bits');
print 'strModulusHex = ', $strModulusHex, "\n";
print "----\n";

# We need the modulus as base64.
my $bd = Chilkat2::BinData->new;
$bd->AppendEncoded($strModulusHex, 'hex');
my $modulus64 = $bd->GetEncoded('base64');
print 'modulus64 = ', $modulus64, "\n";
print "----\n";

# Build the XML for the public key.
my $xmlPubKey = Chilkat2::Xml->new;
$xmlPubKey->Tag('RSAPublicKey');
$xmlPubKey->UpdateChildContent('Modulus', $modulus64);
# The RSA exponent will always be decimal 65537 (base64 = AQAB)
$xmlPubKey->UpdateChildContent('Exponent', 'AQAB');

print "RSA public key as XML:\n";
print $xmlPubKey->GetXml(), "\n";
print "----\n";

# Load the XML into a Chilkat public key object.
my $pubkey = Chilkat2::PublicKey->new;
$success = $pubkey->LoadFromString($xmlPubKey->GetXml());
if (!$success) {
    print $pubkey->LastErrorText, "\n";
    exit;
}

# Show the public key as PEM.
my $preferPkcs1 = 1;
print $pubkey->GetPem($preferPkcs1), "\n";