Perl Requires Chilkat v11.0.0+
Chilkat2 Perl
Backup Windows Current User / Personal Certificates to a .zip
See more Certificates Examples
Demonstrates how to backup the certificates in the Windows registry-based Current User certificate store (in the "Personal" Logical Store as seen in certmgr.msc), to a zip archive. Certificates having an exportable private key are exported to .pfx files. Certificates with no private key, or with a non-exportable private key, are exported to .cer files.Obviously, this example only runs on Windows computers.
Chilkat Perl Downloads
use strict;
use warnings;
use Chilkat2;
my $certStore = Chilkat2::CertStore->new;
my $readOnly = 1;
my $success = $certStore->OpenCurrentUserStore($readOnly);
if (!$success) {
print $certStore->LastErrorText, "\n";
exit;
}
my $pfxPassword = 'secret';
my $allSuccess = 1;
my $numSuccess = 0;
my $zip = Chilkat2::Zip->new;
$zip->NewZip('qa_output/personalCerts.zip');
my $certData = Chilkat2::BinData->new;
my $sbFilename = Chilkat2::StringBuilder->new;
# Iterate over the certificates in the Current User store.
my $cert = Chilkat2::Cert->new;
my $numCerts = $certStore->NumCertificates;
my $i = 0;
while ($i < $numCerts) {
$certStore->GetCert($i, $cert);
print 'DN = ', $cert->SubjectDN, "\n";
$sbFilename->SetString('cert');
$sbFilename->AppendInt($i + 1);
my $bHasPrivateKey = $cert->HasPrivateKey();
if (($bHasPrivateKey) && ($cert->PrivateKeyExportable)) {
# Export to a .pfx
$success = $cert->ExportToPfxBd($pfxPassword, 1, $certData);
if ($success) {
$sbFilename->Append('.pfx');
$zip->AddBd($sbFilename->GetAsString(), $certData);
}
} else {
# Export to a .cer
$success = $cert->ExportCertDerBd($certData);
if ($success) {
$sbFilename->Append('.cer');
$zip->AddBd($sbFilename->GetAsString(), $certData);
}
}
if (!$success) {
$allSuccess = 0;
} else {
$numSuccess = $numSuccess + 1;
}
$i = $i + 1;
}
if ($numSuccess > 0) {
$success = $zip->WriteZipAndClose();
if (!$success) {
print $zip->LastErrorText, "\n";
$allSuccess = 0;
}
}
print 'All success = ', ($allSuccess ? 1 : 0), "\n";