How can I use different certificates on specific connections?

后端 未结 5 2010
星月不相逢
星月不相逢 2020-11-22 01:22

A module I\'m adding to our large Java application has to converse with another company\'s SSL-secured website. The problem is that the site uses a self-signed certificate.

5条回答
  •  無奈伤痛
    2020-11-22 01:29

    I've had to do something like this when using commons-httpclient to access an internal https server with a self-signed certificate. Yes, our solution was to create a custom TrustManager that simply passed everything (logging a debug message).

    This comes down to having our own SSLSocketFactory that creates SSL sockets from our local SSLContext, which is set up to have only our local TrustManager associated with it. You don't need to go near a keystore/certstore at all.

    So this is in our LocalSSLSocketFactory:

    static {
        try {
            SSL_CONTEXT = SSLContext.getInstance("SSL");
            SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Unable to initialise SSL context", e);
        } catch (KeyManagementException e) {
            throw new RuntimeException("Unable to initialise SSL context", e);
        }
    }
    
    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
        LOG.trace("createSocket(host => {}, port => {})", new Object[] { host, new Integer(port) });
    
        return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
    }
    

    Along with other methods implementing SecureProtocolSocketFactory. LocalSSLTrustManager is the aforementioned dummy trust manager implementation.

提交回复
热议问题