Public key verification always returns "Signature does not match"

18,127

You shouldn't be passing in the public key that you extracted from the certificate. You should be passing in the public key of the issuer's certificate to verify the signature.

So, as Robert pointed out in comments, your above code only works if it's a self-signed certificate (the certificate is signed with itself).

Share:
18,127
Java_bear
Author by

Java_bear

Updated on July 20, 2022

Comments

  • Java_bear
    Java_bear almost 2 years

    I am trying to verify the public key of a certificate. The certificate has been imported into a keystore using this command:

    keytool -importcert -file cert.cer -keystore kstore.jks -alias mycert -storepass changeit
    

    This is the java code I use to verify the public key:

    File keyStore = new File("kstore.jks");
    String keyStorePassword = "changeit";
    KeyStore ks = null;
    try {
       ks = KeyStore.getInstance("jks");
       ks.load(keyStore.toURI().toURL().openStream(), keyStorePassword.toCharArray());
    } catch (Exception e) {
       e.printStackTrace();
    } 
    
    try {
       Certificate cert = ks.getCertificate("mycert");
       PublicKey pk = cert.getPublicKey();
       cert.verify(pk);
       //cert.verify(pk, "SunRsaSign");
       System.out.println("Keys verified");
    } catch (Exception e) {
       e.printStackTrace();
    }
    

    The exception I get is:

    java.security.SignatureException: Signature does not match.
       at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:446)
       at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:389)
       at VerifyEBXMLSignature.runIt3(VerifyEBXMLSignature.java:62)
       at VerifyEBXMLSignature.main(VerifyEBXMLSignature.java:41)
    

    The certificate contains a public key and I do not have access to the private key. Is it at all possible to verify the public key against this certificate that I import into a keystore? The public key comes from the certificate itself, so it should be correct.

    What more should I look for with the certificate?

    I just got some more iformation about the certificate: It is exported from the private key. Is there anything in that process that may have be done wrong?

  • Java_bear
    Java_bear over 11 years
    Yes, that seems to be correct. I got the original certificate and it passes the verification without error.