如果设置了适当的属性,X509TrustManagerImpl.checkServerTrusted()是否自己处理OCSP? [英] Does X509TrustManagerImpl.checkServerTrusted() handle OCSP by itself if the appropriate properties are set?

查看:398
本文介绍了如果设置了适当的属性,X509TrustManagerImpl.checkServerTrusted()是否自己处理OCSP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    public class CustomTrustManager implements X509TrustManager {

   private X509TrustManager trustManager;
   // If a connection was previously attempted and failed the certificate check, that certificate chain will be saved here.
   private Certificate[] rejectedCertificates = null;
   private Certificate[] encounteredCertificates = null;
   private KeyStore keyStore = null;
   private Logger logger;

   /**
    * Constructor
    *
    * @param loggerFactory
    *           see {@link InstanceLoggerFactory}
    */
   public CustomTrustManager(InstanceLoggerFactory loggerFactory) {
      try {
         this.logger = loggerFactory.getLogger(CustomTrustManager.class);
         keyStore = KeyStore.getInstance("JKS");
         // a keyStore must be initialized with load, even if certificate trust is not file based.
         keyStore.load(null, null);

         System.setProperty("com.sun.net.ssl.checkRevocation", "true");
         Security.setProperty("ocsp.enable", "true");
      } catch (Exception ex) {
         logger.error("Problem initializing keyStore", ex);
      }
   }

   /**
    * Returns the rejected certificate based on the last usage
    */
   public Certificate[] getRejectedCertificateChain() {
      return rejectedCertificates;
   }

   /**
    * Returns the encountered certificates based on the last usage
    */
   public Certificate[] getEncounteredCertificates() {
      return encounteredCertificates;
   }

   @Override
   public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
      if (trustManager != null) {
         trustManager.checkClientTrusted(chain, authType);
      }
   }

   /**
    * Checks if a server is trusted, based on the wrapped keyStore's trust
    * anchors. This will also capture the encountered certificate chain and, if
    * trust fails, the rejected certificate chain.
    */
   @Override
   public void checkServerTrusted(X509Certificate[] chain, String authType) throws CustomCertificateException {
      // Capture the certificate if it fails
      try {
         encounteredCertificates = chain;
         if (trustManager != null) {
            trustManager.checkServerTrusted(chain, authType);
         } else {
            throw new RuntimeException("Trust manager is null");
         }
      } catch (CertificateException ex) {
         rejectedCertificates = chain;
         throw new CustomCertificateException(ex, rejectedCertificates);
      } catch (Exception ex) {
         rejectedCertificates = chain;
         throw new CustomCertificateException(new CertificateException(ex), rejectedCertificates);
      }
   }

   @Override
   public X509Certificate[] getAcceptedIssuers() {
      return trustManager == null ? new X509Certificate[0] : trustManager.getAcceptedIssuers();
   }

   /**
    * initializes the internal trust manager with all known certificates
    * certificates are stored in the keyStore object
    */
   private void initTrustManager() {
      try {
         // initialize a new TMF with our keyStore
         TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX", "SunJSSE");

         // keyStore must not be empty
         CertPathParameters pkixParams = new PKIXBuilderParameters(keyStore, new X509CertSelector());
         ((PKIXBuilderParameters) pkixParams).setRevocationEnabled(true);

         tmf.init(new CertPathTrustManagerParameters(pkixParams));

         // acquire X509 trust manager from factory
         TrustManager tms[] = tmf.getTrustManagers();
         for (TrustManager tm : tms) {
            if (tm instanceof X509TrustManager) {
               trustManager = (X509TrustManager) tm;
               break;
            }
         }
      } catch (Exception ex) {
         logger.error("Problem initializing trust manager", ex);
      }
   }

 ...
}

这里我实现了X509TrustManager信任管理器,并尝试将相应的检查调用委托给运行时找到的x509信任管理器。
我的问题是我设置的关于 OCSP 的属性是否足以确保Java在验证证书链时也会执行OCSP?换句话说,如果设置了属性, checkServerTrusted()方法会自动处理吗?

Here I've implemented X509TrustManager trust manager and tried to delegate the appropriate checking calls to the x509 trust manager found at run time. My question is are the properties I've set regarding to OCSP enough to be sure that Java will also do OCSP while validating the certificate chain? In other words will checkServerTrusted() method handle that by itself if the properties are set?

推荐答案

看起来您不是通过OCSP检查撤销。以下是如何执行此操作的示例。您将需要目标证书和响应者URL。我从一个工作示例中提取了它并将其修改为尽可能通用。没有测试过,但它应该工作或非常接近工作。您可能需要根据需要定制它,但不是很多。

It does not look like you're checking the revocation via OCSP. Here is an example of how to do this. You will need the target certificate and the responder URL. I extracted this from a working example and modified it to be as generic as possible. Have not tested it, but it should work or be very close to working. You might have to tailor it to your needs, but not by much.

    private void validateCertPath(X509Certificate targetCertificate, X509Certificate issuerCertificate, String responderURL, String trustAnchorDirectory) 
            throws  CertPathValidatorException, 
                            InvalidAlgorithmParameterException, 
                            FileNotFoundException, 
                            CertificateException, 
                            NoSuchAlgorithmException {

    List<X509Certificate> certList = new Vector<X509Certificate>();
    certList.add(targetCertificate);
    certList.add(issuerCertificate);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    CertPath cp = cf.generateCertPath(certList);

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");

    Set<TrustAnchor> trustStore = new HashSet<TrustAnchor>();
    TrustAnchor anchor = null;
    X509Certificate cacert = null;
    File directory = new File(trustAnchorDirectory);
    String certFileNames[] = directory.list();

    for (String certFile : certFileNames) {
        cacert = readCert(trustAnchorDirectory +"/" + certFile);
        anchor = new TrustAnchor(cacert, null);
        trustStore.add(anchor);
    }

    PKIXParameters params = new PKIXParameters(trustStore);
    params.setRevocationEnabled(true);

    Security.setProperty("ocsp.enable", "true");
    Security.setProperty("ocsp.responderURL", responderUrl);

    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
    System.out.println("Certificate validated");
    System.out.println("Policy Tree:\n" + result.getPolicyTree());

}

这篇关于如果设置了适当的属性,X509TrustManagerImpl.checkServerTrusted()是否自己处理OCSP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆