Search code examples
javacryptographybouncycastlejce

Java verify Certificate is associated with a Key


I have a Certificate and a PrivateKey that I've received from different places. Given just these two abstract objects, can I verify that the Certificate is associated with, or is the Certificate for the given PrivateKey?

I understand if these are for RSA keys, I can cast them to RsaPublicKey / RsaPrivateKey and verify that the exponent and modulus match, but what if they are ECDSA? What about other types?

I eventually want to store the Key into a a Keystore with the Certificate as its certificate chain and I expected this to throw an exception or cause some sort of error if I tried loading a key with a certificate from another key. But it doesn't seem to matter?


Solution

  • First of all, to be sure, you can sign random block of data with your private key and verify it with a public key. The public key is a part of the certificate. It works for all signature algorithms.

    It is also very common that a private key structure contains the matching public key. You should check it - searching a matching key will be easier then.