title: Java - verifying certificate with system TrustStore
body: <p>Premise: I have a certificate and I want to verify that the <strong>system</strong> 'trusts' this certificate (signed by a trusted root CA by Java / Operating System)</p>
  
  <p>I have found some varying solutions on how to accomplish this.</p>
  
  <p>Option 1:</p>
  
  <p>Use SSL classes to derive trust.</p>
  
  <pre><code>TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  tmfactory.init((KeyStore) null);
  for (TrustManager trustManager : tmfactory.getTrustManagers()) {
      if (trustManager instanceof X509TrustManager) {
          try {
              ((X509TrustManager) trustManager).checkClientTrusted(new X509Certificate[] {new JcaX509CertificateConverter().getCertificate(holder)}, "RSA");
              System.out.println("This certificate is trusted by a Root CA");
          } catch (CertificateException e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>
  
  <p>Since this approach relies heavily on SSL classes (which are not needed by the current project) we are looking for alternatives.</p>
  
  <p>Option 2:
  Load Java's <code>cacerts</code>file into a keystore and check each 'most-trusted' certificate against my certificate for equality.</p>
  
  <pre><code>String filename = System.getProperty("java.home") + "/lib/security/cacerts".replace('/', File.separatorChar);
  FileInputStream is = new FileInputStream(filename);
  KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
  String password = "changeit";
  keystore.load(is, password.toCharArray());
  
  // This class retrieves the most-trusted CAs from the keystore
  PKIXParameters params = new PKIXParameters(keystore);
  // Get the set of trust anchors, which contain the most-trusted CA certificates
  Set&lt;X509Certificate&gt; rootCertificates = params.getTrustAnchors().parallelStream().map(TrustAnchor::getTrustedCert).collect(Collectors.toSet());
  return rootCertificates.contains(holderX509);
  </code></pre>
  
  <p>The problem with this approach is that it requires a password to verify integrity of the JKS encoded file. While the SSL one seemingly does not (or rather uses <code>System.getProperty("javax.net.ssl.trustStorePassword")</code> which again is heavily tied to SSL.</p>
  
  <p>Question: Does there exist a solution that is in between manually loading certificates from a file and pure SSL? I feel as if there should be some class that I can call to simply verify the system trust of a certificate without having to jump through a couple hoops.</p>