En Lora Ilieva En Lora Ilieva - 3 months ago 39
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: ",
$oref_x509->error;
}


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.

Answer

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

-----BEGIN CERTIFICATE-----
MIICVTCCAbegAwIBAgIELwBe7DAKBggqhkjOPQQDAjAaMRgwFgYDVQQDDA9mb28u
....
-----END CERTIFICATE-----

you should decode only the base64 part:

MIICVTCCAbegAwIBAgIELwBe7DAKBggqhkjOPQQDAjAaMRgwFgYDVQQDDA9mb28u
....

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

Comments