Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 702
Java_bear Avatar asked Aug 28 '12 09:08

Java_bear


1 Answers

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

like image 103
Marcus Adams Avatar answered Nov 09 '22 13:11

Marcus Adams