简体   繁体   中英

Question about Crypt::OpenSSL::RSA->verify method

My question is about this: https://metacpan.org/pod/Crypt::OpenSSL::RSA

If there described method verify() fails, I do error handling like this:

my $rsa_pub = Crypt::OpenSSL::RSA->new_public_key($x509PubKey);
logm("exception: my err msg...") unless $rsa_pub->verify($text, $signature);

But is it possible get exact reason why verification failed?

I'm not sure that getting "the exact reason why verification failed" makes sense as a question. To verify a signature you specify:

  • the signature algorithm
  • the padding algorithm
  • the hashing function

Ultimately the signature is just a number that was computed by padding the the plaintext input, hashing the resulting bytes and performing a mathematical calculation using the private key.

Verifying the signature involves taking the plaintext, padding it, hashing it, and performing a mathematical calculation using the public key to produce another number which is then compared to the number from the signature (using modulo arthimetic?). If the numbers are the same then the signature is valid if they're different, it's not.

All of which is a roundabout way of saying if the verify method returns false then assuming you're using the correct public key, one of these things must be different:

  • the plaintext
  • the signature algorithm
  • the padding algorithm
  • the hashing function

But there's really no way of knowing which. It's like saying "I'm trying to multiply two numbers to get 42, but I don't get 42, which of the numbers is wrong?".

Here are a couple of signature verification functions for common combinations of algorithms (which I wrote for Authen::NZRealMe::XMLSig ):

sub _verify_signature_rsa_sha1 {
    my($self, $plaintext, $bin_sig) = @_;
    my $rsa_pub_key = Crypt::OpenSSL::RSA->new_public_key($self->pub_key_text);
    $rsa_pub_key->use_pkcs1_padding();
    $rsa_pub_key->use_sha1_hash();
    return $rsa_pub_key->verify($plaintext, $bin_sig);
}


sub _verify_signature_rsa_sha256 {
    my($self, $plaintext, $bin_sig) = @_;
    my $rsa_pub_key = Crypt::OpenSSL::RSA->new_public_key($self->pub_key_text);
    $rsa_pub_key->use_pkcs1_oaep_padding();
    $rsa_pub_key->use_sha256_hash();
    return $rsa_pub_key->verify($plaintext, $bin_sig);
}

The context for the above code is signed sections of XML documents, which has the added complexity of needing to use the right canonicalization and encoding and also the signature data is Base64 encoded so needs to be decoded into bytes first.

The information about which padding and hashing algorithms to use should be available from the spec for the source data you're working with, but if not I guess you could try random combinations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM