Search code examples
perlsslopensslx509

Cannot get any results with Net::SSLeay for openssl


I am trying to create a script that looks at the data for my certs in my ~/ssl/certs folder and displays the issuer information to me.

It's written in perl and it would be easy to just say:

$data = `/usr/bin/openssl x509 -in $file -noout -issuer`

However that is not very portable. I am trying to use Net::SSLeay instead to get the same output, however all I can seem to manage are checksum numbers, what am I missing? Here is what I got

#!/usr/bin/perl
use 5.10.1;
use strict;
use warnings;
use Net::SSLeay qw(die_now die_if_ssl_error);
Net::SSLeay::load_error_strings();
Net::SSLeay::SSLeay_add_ssl_algorithms();    # Important!
Net::SSLeay::ENGINE_load_builtin_engines();  # If you want built-in engines
Net::SSLeay::ENGINE_register_all_complete(); # If you want built-in engines
Net::SSLeay::randomize();
Net::SSLeay::library_init();
Net::SSLeay::OpenSSL_add_all_algorithms();
my $file = '~/ssl/certs/certificate.crt';

my $x509 = Net::SSLeay::X509_new(); 
Net::SSLeay::X509_free($x509);
my $type = Net::SSLeay::X509_certificate_type($x509);
my $ctx = Net::SSLeay::CTX_new_with_method(Net::SSLeay::TLSv1_method());
my $test = Net::SSLeay::X509_load_cert_file( $ctx, $file, $type );
my $info = Net::SSLeay::X509_issuer_name_hash($x509);

say "\nInfo = $info \nX509 = $x509\nTest= $test\nType = $type\nCTX = $ctx";



This is my output:
Info = 4003674586 
X509 = 16119648
Test= 0
Type = 0
CTX = 16137888

I've read through all the source code and the documentation, none of it makes any sense.


Solution

  • You don't need all this context etc. After you've initialized the SSL library you can simply do:

    my $bio = Net::SSLeay::BIO_new_file($file,'r') or die $!;
    my $cert = Net::SSLeay::PEM_read_bio_X509($bio);
    Net::SSLeay::BIO_free($bio);
    $cert or die "cannot parse $file as PEM X509 cert: ".
        Net::SSLeay::ERR_error_string(Net::SSLeay::ERR_get_error());
    my $issuer = Net::SSLeay::X509_NAME_oneline(
        Net::SSLeay::X509_get_issuer_name($cert));