SSL 之 http只用crt格式证书完成SSL单向认证通信

SSL 之 http只用crt格式证书完成SSL单向认证通信背景 远程调用第三方服务时,之前都是双向认证,服务器提供jks格式的keystore证书,客户端配置好即可。 今天遇到个奇葩需求&#xff

背景

以前远程调用第三方服务时,采用的是双向认证,服务器提供jks格式的keystore证书,客户端可以配置。

今天,服务器仅提供根公钥证书(root.crt)。这是第三方合法证书,在SSL 期间验证服务器发送的证书时需要单向身份验证。握手时只给出crt公钥。我真的同意。我别无选择,只能自己上网摸索。下面是适合我的情况的代码练习。测试没有什么问题。供你参考。

代码

//该类实现证书验证

导入javax.net.ssl.X509TrustManager。

导入java.security.*。

导入java.security.cert.CertificateException。

导入java.security.cert.X509Certificate。

公共类CustomTrustManager 实现X509TrustManager {

私有静态最终记录器日志=LoggerFactory.getLogger(CustomTrustManager.class);

私有最终X509 证书rootCert;

公共CustomTrustManager(X509Certificate rootCert) {

this.rootCert=根证书;

}

@覆盖

公共无效checkClientTrusted(X509Certificate []链,字符串authType)抛出CertificateException {

//根据你的要求实现检查逻辑

}

@覆盖

公共无效checkServerTrusted(X509Certificate []链,字符串authType)抛出CertificateException {

布尔值找到=false;

最终公钥publicKey=rootCert.getPublicKey();

for (X509Certificate cert : 链) {

尝试{

证书.验证(公钥);

发现=真;

休息;

catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | }

NoSuchProviderException e) {

log.error(\’客户端证书验证失败\’, e);

}

}

如果(!找到){

throw new CertificateException(\’在服务器的证书链中找不到受信任的证书。\’);

}

}

@覆盖

公共X509Certificate[] getAcceptedIssuers() {

返回新的X509Certificate[]{}。

}

}

测试代码

@测试

void testCerts() 抛出NoSuchAlgorithmException、KeyManagementException、IOException {

//Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

X509证书;

//加载根证书

尝试(InputStream inputStream=new FileInputStream(\’D:\\\\certs\\\\root-new.crt\’)){

CertificateFactory 证书工厂=CertificateFactory.getInstance(\’X.509\’);

证书=(X509Certificate)certificatefactory.generateCertificate(inputStream);

catch (IOException | java.security.cert.CertificateException e) {

抛出一个新的RuntimeException(e)。

}

X509证书rootCert=证书;

//创建SSL 上下文并将所有证书设置为信任。

SSLContext sslContext=SSLContext.getInstance(\’TLS\’);

sslContext.init(null, new TrustManager[]{new CustomTrustManager(rootCert)}, null);

//获取HttpsURLConnection 实例

HttpsURLConnection 连接=(HttpsURLConnection) new URL(\’https://URI\’).openConnection();

连接.setSSLSocketFactory(sslContext.getSocketFactory());

连接.connect();

System.out.println(\’2222222222\’);

断开();

System.out.println(\’11111111111\’);

}

就这样!

以上关于#SSL http的信息仅使用crt格式的证书来完成SSL单向认证通信。相关信息请参见官方公告。

原创文章,作者:CSDN,如若转载,请注明出处:https://www.sudun.com/ask/92266.html

(0)
CSDN的头像CSDN
上一篇 2024年6月26日
下一篇 2024年6月26日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注