使用 java 代码将证书添加到密钥库 [英] Adding certificate to keystore using java code

查看:23
本文介绍了使用 java 代码将证书添加到密钥库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用服务器的 .cer 证书文件建立 https 连接.我可以使用浏览器手动获取证书文件,并使用 keytool 将其放入密钥库.然后我可以使用 java 代码访问密钥库,获取我添加到密钥库的证书并连接到服务器.

I'm trying to establish a https connection using the server's .cer certificate file. I am able to manually get the certificate file using a browser and put it into the keystore using keytool. I can then access the keystore using java code, obtain the certificate i added to the keystore and connect to the server.

然而,我现在甚至想要使用 java 代码实现获取证书文件并将其添加到我的密钥库的过程,而不使用 keytool 或浏览器来获取证书.

I now however want to implement even the process of getting the certificate file and adding it to my keystore using java code and without using keytool or browser to get certificate.

有人可以告诉我如何处理这个问题以及我需要做什么吗?

Can someone please tell me how to approach this and what I need to do?

推荐答案

似乎完全符合您的要求.

This seems to do exactly what you want.

使用以下代码可以在运行时添加信任存储.

Using the following code it is possible to add a trust store during runtime.

import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

public class SSLClasspathTrustStoreLoader {
    public static void setTrustStore(String trustStore, String password) throws Exception {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream keystoreStream = SSLClasspathTrustStoreLoader.class.getResourceAsStream(trustStore);
        keystore.load(keystoreStream, password.toCharArray());
        trustManagerFactory.init(keystore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustManagers, null);
        SSLContext.setDefault(sc);
    }
}

我使用此代码与活动目录服务器建立安全的 LDAP 连接.

I used this code to establish a secure LDAP connection with an active directory server.

也有用,底部有一个类,可以在运行时导入证书.

This could also be usful, at the bottom there is a class, which is able to import a certificate during runtime.

这篇关于使用 java 代码将证书添加到密钥库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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