Java SSL 连接,以编程方式将服务器证书添加到密钥库

问题描述:

我正在将 SSL 客户端连接到我的 SSL 服务器.当由于客户端密钥库中不存在根而导致客户端无法验证证书时,我需要选择将该证书添加到代码中的本地密钥库并继续.有一些始终接受所有证书的示例,但我希望用户在不离开应用程序的情况下验证证书并将其添加到本地密钥库.

I am connecting an SSL client to my SSL server. When the client fails to verify a certificate due to the root not existing in the client's key store, I need the option to add that certificate to the local key store in code and continue. There are examples for always accepting all certificates, but I want the user to verify the cert and add it to local key store without leaving the application.

SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("localhost", 23467);
try{
    sslsocket.startHandshake();
} catch (IOException e) {
    //here I want to get the peer's certificate, conditionally add to local key store, then reauthenticate successfully
}

有很多关于自定义 SocketFactory、TrustManager、SSLContext 等的东西,我真的不明白它们是如何组合在一起的,或者哪一条是实现我的目标的最短路径.

There is a whole lot of stuff about custom SocketFactory, TrustManager, SSLContext, etc and I don't really understand how they all fit together or which would be the shortest path to my goal.

您可以使用 X509TrustManager.

使用

SSLContext ctx = SSLContext.getInstance("TLS");

然后使用 SSLContext#init.SecureRandom 和 KeyManager[] 可能为空.后者仅在您执行客户端身份验证时有用,如果在您的场景中只有服务器需要身份验证,则无需设置.

Then initialize it with your custom X509TrustManager by using SSLContext#init. The SecureRandom and the KeyManager[] may be null. The latter is only useful if you perform client authentication, if in your scenario only the server needs to authenticate you don't need to set it.

从此 SSLContext 中,使用 SSLContext#getSocketFactory 并按计划进行.

From this SSLContext, get your SSLSocketFactory using SSLContext#getSocketFactory and proceed as planned.

就您的 X509TrustManager 实现而言,它可能如下所示:

As concerns your X509TrustManager implementation, it could look like this:

TrustManager tm = new X509TrustManager() {
    public void checkClientTrusted(X509Certificate[] chain,
                    String authType)
                    throws CertificateException {
        //do nothing, you're the client
    }

    public X509Certificate[] getAcceptedIssuers() {
        //also only relevant for servers
    }

    public void checkServerTrusted(X509Certificate[] chain,
                    String authType)
                    throws CertificateException {
        /* chain[chain.length -1] is the candidate for the
         * root certificate. 
         * Look it up to see whether it's in your list.
         * If not, ask the user for permission to add it.
         * If not granted, reject.
         * Validate the chain using CertPathValidator and 
         * your list of trusted roots.
         */
    }
};

Ryan 是对的,我忘了解释如何将新根添加到现有根中.假设您当前的受信任根密钥库源自 cacerts(JDK 附带的Java 默认信任库",位于 jre/lib/security 下).我假设您使用 KeyStore#load(InputStream, char[]) 加载了该密钥库(采用 JKS 格式).

Ryan was right, I forgot to explain how to add the new root to the existing ones. Let's assume your current KeyStore of trusted roots was derived from cacerts (the 'Java default trust store' that comes with your JDK, located under jre/lib/security). I assume you loaded that key store (it's in JKS format) with KeyStore#load(InputStream, char[]).

KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream in = new FileInputStream("<path to cacerts"");
ks.load(in, "changeit".toCharArray);

cacerts 的默认密码是changeit",如果您还没有更改它.

The default password to cacerts is "changeit" if you haven't, well, changed it.

然后您可以使用 KeyStore#setEntry.您可以省略 ProtectionParameter(即 null),KeyStore.Entry 将是 TrustedCertificateEntry 将新根作为其构造函数的参数.

Then you may add addtional trusted roots using KeyStore#setEntry. You can omit the ProtectionParameter (i.e. null), the KeyStore.Entry would be a TrustedCertificateEntry that takes the new root as parameter to its constructor.

KeyStore.Entry newEntry = new KeyStore.TrustedCertificateEntry(newRoot);
ks.setEntry("someAlias", newEntry, null);

如果您想在某个时候保留更改的信任存储,您可以使用 KeyStore#store(OutputStream, char[].

If you'd like to persist the altered trust store at some point, you may achieve this with KeyStore#store(OutputStream, char[].