rjschwei has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

Loads of Google searches and lots of reading have not led me to the desired result.

I have data that was signed by someone else. I also have the signature and I have a certificate. I want to verify in Perl that the data has not been fiddled with.

In Python this works for me as follows:
from M2Crypto import X509 def verify_data(data, signature, cert): rawsig = signature..decode('base64') x509 = X509.load_cert_string(cert) pubkey = x509.get_pubkey() pubkey.reset_context(md='sha256') pubkey.verify_init() pubkey.verify_update(data) return pubkey.verify_final(rawsig)
How would I do this in Perl?

All the X509 things I have found appear to have options to deal with the certificate itself, but I haven't found the next step, i.e.

my $x509 = Crypt::OpenSSL::X509->new_from_file('cert.pm'); my $pubkey = $x509->pubkey(); my $signature = read_file('signature.txt' , binmode => ':raw' ); my $data = read_file('data.txt' , binmode => ':raw' );
But what happens next, as in Python I'd now like to call some methods that verify the signature and data against the public key....

The openssl dgst command does not handle a cert and extracting the public key didn't lead to the desired result:

openssl x509 -in cert.pem -pubkey >& pubkey.txt openssl dgst -sha256 -verify pubkey.txt -signature signature.txt myDat +a.txt
The verification with openssl fails, but it should be valid and is valid with the Python code above. Help is much appreciated.

Replies are listed 'Best First'.
Re: Verify signed data
by tobyink (Canon) on May 23, 2014 at 02:31 UTC

    If you're extracting a public key from an X.509 certificate, then you probably want to use RSA. I've found Crypt::OpenSSL::RSA to be a pretty good module for doing RSA.

    It is possible to embed other key types (non-RSA, such as DSA) into an X.509 certificate, but that doesn't yet seem common.

    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name
      Thanks for pointing me in the right direction.
Re: Verify signed data
by Anonymous Monk on May 23, 2014 at 01:59 UTC
Re: Verify signed data
by rjschwei (Novice) on May 23, 2014 at 17:09 UTC
    With the pointer to the RSA module the following code does the trick for me :)
    use Crypt::OpenSSL::RSA; use Crypt::OpenSSL::X509; use File::Slurp; use MIME::Base64; my $x509 = Crypt::OpenSSL::X509->new_from_file('cert.pem'); my $pubkey = Crypt::OpenSSL::RSA->new_public_key($x509->pubkey()); $pubkey->use_sha256_hash(); my $sigbase64 = read_file('signature.txt' , binmode => ':raw' ); my $data = read_file('data.txt' , binmode => ':raw' ); my $signature = decode_base64($sigbase64); my $valid = $pubkey->verify($data, $signature); print "Is valid: $valid\n";
    this is equivalent to the Python code posted in the original question.