En Lora Ilieva En Lora Ilieva - 8 months ago 83
Perl Question

Extract data from certificate with perl Crypt::X509

I'm trying to extract the data from a .pem certificate with the Crypt::X509 library, but I get an error in object construction.
Here is what I'm doing:
1. Read the .pem file's content:

my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
$atime,$mtime,$ctime,$blksize,$blocks) = stat $s_filename;
open FILE, "<$s_filename" or die "no such file";
binmode FILE;
my $pem_cert;
read FILE, $pem_cert, $size;
close FILE;

2. Decode the content from base64 to receive the DER formatted content. This is done because the CPAN documentation of the Crypt::X509 library states that it needs to be passed:

A variable containing the DER formatted certificate to be parsed

my $der = MIME::Base64::decode($pem_cert);

  1. Call the Crypt::X509 constructor and check for errors:

my $oref_x509= Crypt::X509->new(cert=>$der);
if ( $oref_x509->error ) {
warn "Error on parsing certificate: ",

I get the following error:

Error on parsing certificate: decode error 04<=>30 0 8 at ..<path>../Convert/ASN1/_decode.pm line 113.

I've tried with other certificate, but the error is the same.


When converting the certificate from PEM to DER using MIME::Base64::decode you need to remove the PEM header and trailer, i.e. instead of decoding


you should decode only the base64 part:


Since -----BEGIN CERTIFICATE----- etc contain valid base64 characters they will be used for decoding and the invalid characters silently ignored.