SSLSocketFactory使用预安装CA.

时间:2018-05-17 12:44:38

标签: java security ssl tls1.2

我创建了一个SSLSocketFactory,在给定信任存储的情况下加载TrustManagerFactory,如下所示。我想知道有一种方法可以创建一个加载所有预安装证书的SSL工厂(与浏览器类似)。换句话说,接受计算机/ docker容器/ JVM已经拥有的所有证书。 (我不是安全专家,我希望这个问题足够了。)

/**
 * Provide a quick method to construct a SSLSocketFactory which is a TCP socket using TLS/SSL
 * @param trustStore location of the trust store
 * @param keyStore location of the key store
 * @param trustStorePassword password to access the trust store
 * @param keyStorePassword password to access the key store
 * @return the SSLSocketFactory to create secure sockets with the provided certificates infrastructure
 * @exception java.lang.Exception in case of something wrong happens
 * */
static public SSLSocketFactory getSocketFactory ( final String trustStore, final String keyStore, final String trustStorePassword, final String keyStorePassword) throws Exception
{

    // todo check if the CA needs or can use the password
    final FileInputStream trustStoreStream = new FileInputStream(trustStore);
    final FileInputStream keyStoreStream = new FileInputStream(keyStore);
    // CA certificate is used to authenticate server
    final KeyStore caKs = KeyStore.getInstance("JKS");
    caKs.load(trustStoreStream, trustStorePassword.toCharArray());
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
    tmf.init(caKs);

    trustStoreStream.close();

    // client key and certificates are sent to server so it can authenticate us
    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(keyStoreStream, keyStorePassword.toCharArray());
    final KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
    kmf.init(ks, keyStorePassword.toCharArray());

    keyStoreStream.close();

    // finally, create SSL socket factory
    final SSLContext context = SSLContext.getInstance("TLSv1.2");
    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}

谢谢!

0 个答案:

没有答案