TrustManager加载默认的JRE信任证书

Easter79
• 阅读 446

https://stackoverflow.com/questions/24555890/using-a-custom-truststore-in-java-as-well-as-the-default-one

Essentially, get hold of the default trust manager, create a second trust manager that uses your own trust store. Wrap them both in a custom trust manager implementation that delegates call to both (falling back on the other when one fails).

TrustManagerFactory tmf = TrustManagerFactory
    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
// Using null here initialises the TMF with the default trust store.
tmf.init((KeyStore) null);

// Get hold of the default trust manager
X509TrustManager defaultTm = null;
for (TrustManager tm : tmf.getTrustManagers()) {
    if (tm instanceof X509TrustManager) {
        defaultTm = (X509TrustManager) tm;
        break;
    }
}

FileInputStream myKeys = new FileInputStream("truststore.jks");

// Do the same with your trust store this time
// Adapt how you load the keystore to your needs
KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
myTrustStore.load(myKeys, "password".toCharArray());

myKeys.close();

tmf = TrustManagerFactory
    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(myTrustStore);

// Get hold of the default trust manager
X509TrustManager myTm = null;
for (TrustManager tm : tmf.getTrustManagers()) {
    if (tm instanceof X509TrustManager) {
        myTm = (X509TrustManager) tm;
        break;
    }
}

// Wrap it in your own class.
final X509TrustManager finalDefaultTm = defaultTm;
final X509TrustManager finalMyTm = myTm;
X509TrustManager customTm = new X509TrustManager() {
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        // If you're planning to use client-cert auth,
        // merge results from "defaultTm" and "myTm".
        return finalDefaultTm.getAcceptedIssuers();
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain,
            String authType) throws CertificateException {
        try {
            finalMyTm.checkServerTrusted(chain, authType);
        } catch (CertificateException e) {
            // This will throw another CertificateException if this fails too.
            finalDefaultTm.checkServerTrusted(chain, authType);
        }
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain,
            String authType) throws CertificateException {
        // If you're planning to use client-cert auth,
        // do the same as checking the server.
        finalDefaultTm.checkClientTrusted(chain, authType);
    }
};


SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { customTm }, null);

// You don't have to set this as the default context,
// it depends on the library you're using.
SSLContext.setDefault(sslContext);

You don't have to set that context as the default context. How you use it depends on the client library you're using (and where it gets its socket factories from).

This being said, in principle, you'd always have to update the truststore as required anyway. The Java 7 JSSE Reference Guide had an "important note" about this, now downgraded to just a "note" in version 8 of the same guide:

The JDK ships with a limited number of trusted root certificates in the java-home/lib/security/cacerts file. As documented in keytool reference pages, it is your responsibility to maintain (that is, add and remove) the certificates contained in this file if you use this file as a truststore.

Depending on the certificate configuration of the servers that you contact, you may need to add additional root certificates. Obtain the needed specific root certificates from the appropriate vendor.

点赞
收藏
评论区
推荐文章
Wesley13 Wesley13
2年前
C++:获取时间戳
文中代码主要来自http://stackoverflow.com/questions/6012663/getunixtimestampwithc(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2Fstackoverflow.com%2Fquestions%2F601266
Stella981 Stella981
2年前
Opencv中Mat矩阵相乘——点乘、dot、mul运算详解
Opencv中Mat矩阵相乘——点乘、dot、mul运算详解2016年09月02日00:00:36 \牧野(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fme.csdn.net%2Fdcrmg) 阅读数:59593
Wesley13 Wesley13
2年前
ubuntu使用curl加载https报ssh认证失败及dns配置
curl加载https报ssh认证失败原因,系统时间与远程服务时间不一致解决方案:http://stackoverflow.com/questions/21181231/servercertificateverificationfailedcafileetcsslcertscacertificatesc(https://
Stella981 Stella981
2年前
Ajax 跨域请求 Flask 页面请求不到的解决
参考:http://stackoverflow.com/questions/25860304/howdoisetresponseheadersinflask(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2Fstackoverflow.com%2Fquestions%2F2
Wesley13 Wesley13
2年前
unity 用代码控制动画的播放的进度
https://answers.unity.com/questions/1225328/importedanimatedobjectandslidertutorial.html(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fanswers.unity.com%2Fquesti
Easter79 Easter79
2年前
The Complete Guide To Rooting Any Android Phone
PhoneWhitsonGordon(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2Fwww.lifehacker.com.au%2Fauthor%2Fwhitsongordon%2F)7April,20118:00AMShare(https://ww
Stella981 Stella981
2年前
Essential Studio for UWP发布2017 v2,新增甘特图控件
EssentialStudioforUWP(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fwww.evget.com%2Fproduct%2F3894)是包含有35组件的综合套包,包括最快的图表和网格组件。所有组件根据当前被呈现的设备系列自适应渲染。EssentialStu
Stella981 Stella981
2年前
Google地球出现“无法连接到登录服务器(错误代码:c00a0194)”解决方法
Google地球出现“无法连接到登录服务器(错误代码:c00a0194)”解决方法参考文章:(1)Google地球出现“无法连接到登录服务器(错误代码:c00a0194)”解决方法(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fwww.codeprj.com%2Fblo
Stella981 Stella981
2年前
OpenYurt 入门
!头图.png(https://ucc.alicdn.com/pic/developerecology/d35db6f1020a4b85bf70f437903c342d.png)作者| 唐炳昌来源|阿里巴巴云原生公众号(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fmp.
Stella981 Stella981
2年前
Flink SQL Window源码全解析
!(https://oscimg.oschina.net/oscnet/72793fbade36fc18d649681ebaeee4cdf00.jpg)(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzU3MzgwNT
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k