Validating a certificate in java throws an exception - unable to find valid certificate path to requested target

后端 未结 3 1950
遥遥无期
遥遥无期 2020-12-05 09:09

I have a web app that requires a client to send it\'s certificate and the server has to validate the certificate(i.e see if the issuer is a valid issuer and present in the s

3条回答
  •  情话喂你
    2020-12-05 09:33

    Maybe a valid path can't be constructed because some intermediate certificates are missing. Your loop to load certificates discards all but the last. Instead, save all of those certificates, and pass them to the CertPathBuilder to aid in path construction.

    Another common problem is that revocation checks are performed by default, which is good for security. If you don't understand how to obtain a CRL, or utilize OCSP, you can diminish your security and disable revocation checks. This is also shown in the example below.

    ...
    CertificateFactory fac = CertificateFactory.getInstance("X.509");
    FileInputStream is = new FileInputStream("client.crt");
    Collection intermediate;
    try {
      intermediate = fac.generateCertificates(is);
    } finally {
      is.close();
    }
    X509Certificate client = null;
    for (Certificate c : intermediate)
      client = (X509Certificate) c;
    if (client == null)
      throw new IllegalArgumentException("Empty chain.");
    X509CertSelector t = new X509CertSelector();
    t.setCertificate(client);
    PKIXBuilderParameters params = new PKIXBuilderParameters(anchors, t);
    CertStoreParameters store = new CollectionCertStoreParameters(intermediate);
    params.addCertStore(CertStore.getInstance("Collection", store));
    params.setRevocationEnabled(false);
    ...
    

    It would help to know how you are obtaining the "client.crt" file and what its contents are expected to be. Like the responders, I wonder why you can't use the built-in facilities of JSSE to perform this validation.

提交回复
热议问题