X509CertificateUtils { public static boolean privateKeyMatchesPublicKey(PrivateKey privateKey, PublicKey publicKey) { byte[] someRandomData = new byte[64]; new Random().nextBytes(someRandomData); Signature signer = SignatureUtils.createSigner(privateKey); Signature verifier = SignatureUtils.createVerifier(publicKey); try { signer.update(someRandomData); verifier.update(someRandomData); byte[] signature = signer.sign(); return verifier.verify(signature); } catch (SignatureException e) { throw new RuntimeException(e); } } private  X509CertificateUtils(); static X509Certificate fromPem(String pem); static List<X509Certificate> certificateListFromPem(String pem); static String toPem(X509Certificate certificate); static String toPem(List<X509Certificate> certificates); static List<String> getSubjectCommonNames(X509Certificate certificate); static List<String> getIssuerCommonNames(X509Certificate certificate); static List<String> getSubjectOrganizationalUnits(X509Certificate certificate); static List<String> getCommonNames(X500Principal distinguishedName); static List<SubjectAlternativeName> getSubjectAlternativeNames(X509Certificate certificate); static boolean privateKeyMatchesPublicKey(PrivateKey privateKey, PublicKey publicKey);  }
@Test public void verifies_matching_cert_and_key() { KeyPair ecKeypairA = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256); KeyPair ecKeypairB = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256); KeyPair rsaKeypairA = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 1024); KeyPair rsaKeypairB = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 1024); assertTrue(X509CertificateUtils.privateKeyMatchesPublicKey(ecKeypairA.getPrivate(), ecKeypairA.getPublic())); assertTrue(X509CertificateUtils.privateKeyMatchesPublicKey(rsaKeypairA.getPrivate(), rsaKeypairA.getPublic())); assertFalse(X509CertificateUtils.privateKeyMatchesPublicKey(ecKeypairA.getPrivate(), ecKeypairB.getPublic())); assertFalse(X509CertificateUtils.privateKeyMatchesPublicKey(rsaKeypairA.getPrivate(), rsaKeypairB.getPublic())); }