Java_bear
Java_bear

Reputation: 115

Public key verification always returns "Signature does not match"

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?

Upvotes: 11

Views: 21546

Answers (2)

Harbeer Kadian
Harbeer Kadian

Reputation: 394

The public key verify method internally uses X509 Certificate implementation.

So it can only verify those certificates which are generated as per X509 standards.

For more info Visit http://en.wikipedia.org/wiki/X.509

Upvotes: -2

Marcus Adams
Marcus Adams

Reputation: 53870

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).

Upvotes: 11

Related Questions