Sample code for 30+ languages & platforms
Perl Requires Chilkat v9.5.0.49+

Add Private Key and Certificate to a PEM

See more PEM Examples

Demonstrates how to add certificates and private keys to a PEM.

Chilkat Perl Downloads

Chilkat2 Perl
use strict;
use warnings;
use Chilkat2;

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

# The Chilkat PEM class requires the bundle to be unlocked, as shown above.
my $pem = Chilkat2::Pem->new;

# Add the private key found in alice.key to this PEM.
#
my $privKey = Chilkat2::PrivateKey->new;

my $success = $privKey->LoadAnyFormatFile('qa_data/alice.key', '');
if (!$success) {
    print $privKey->LastErrorText, "\n";
    exit;
}

# Add it to the PEM:
$success = $pem->AddPrivateKey($privKey);

# Add the certificate found in alice.crt to this PEM.
#
my $cert = Chilkat2::Cert->new;

$success = $cert->LoadFromFile('qa_data/alice.crt');
if (!$success) {
    print $cert->LastErrorText, "\n";
    exit;
}

# Add it to the PEM:
my $includeCertChain = 0;
$success = $pem->AddCert($cert, $includeCertChain);

# Write the PEM containing the private key and certificate.
# The private key will be output in PKCS8 encrypted form.
# Certificates are never encrypted.

# This is the password that will be required to open and access the private key
# from the PEM we're about to write..
my $password = 'secret';
my $extendedAttrs = 0;
my $noKeys = 0;
my $noCerts = 0;
my $noCaCerts = 0;
my $encryptAlg = 'aes128';

my $pemStr = $pem->ToPemEx($extendedAttrs, $noKeys, $noCerts, $noCaCerts, $encryptAlg, $password);
print $pemStr, "\n";