HTTPClient-1.4.2: Explanation needed for Custom SSL Context Example

前端 未结 1 886
臣服心动
臣服心动 2020-12-16 08:19

This is the example for Custom SSL Context from HttpClient-4.x documentation: http://hc.apache.org/httpcomponents-client-ga/examples.html

Note: removing comments for

相关标签:
1条回答
  • 2020-12-16 08:57

    There are several constructors for SSLSocketFactory. The constructor that the example is using takes only a custom trustStore. You need to use one of the constructors that takes a custom keyStore (which contains your client certificates).

    You only need a custom trustStore if the target server is using a self-signed certificate.

    This example initializes a SSLContext with a custom trustStore and keyStore:

    public static void main(String[] args) throws Exception {
    
        DefaultHttpClient httpClient = new DefaultHttpClient();
    
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            TrustManager[] trustManagers = getTrustManagers("jks", new FileInputStream(new File("cacerts")), "changeit");
            KeyManager[] keyManagers = getKeyManagers("pkcs12", new FileInputStream(new File("clientCert.pfx")), "password");
            ctx.init(keyManagers, trustManagers, new SecureRandom());
            SSLSocketFactory factory = new SSLSocketFactory(ctx, new StrictHostnameVerifier());
    
            ClientConnectionManager manager = httpClient.getConnectionManager();
            manager.getSchemeRegistry().register(new Scheme("https", 443, factory));
    
            //as before
        }
    }
    
    protected static KeyManager[] getKeyManagers(String keyStoreType, InputStream keyStoreFile, String keyStorePassword) throws Exception {
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(keyStoreFile, keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, keyStorePassword.toCharArray());
        return kmf.getKeyManagers();
    }
    
    protected static TrustManager[] getTrustManagers(String trustStoreType, InputStream trustStoreFile, String trustStorePassword) throws Exception {
        KeyStore trustStore = KeyStore.getInstance(trustStoreType);
        trustStore.load(trustStoreFile, trustStorePassword.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        return tmf.getTrustManagers();
    }
    
    0 讨论(0)
提交回复
热议问题