Java怎样判断目标服务器证书颁发者机构是否合法
时间: 2023-07-16 08:14:42 浏览: 49
在 Java 中,可以使用 `javax.net.ssl.HttpsURLConnection` 类来建立 HTTPS 连接,并在连接建立过程中对目标服务器证书进行验证。这个类提供了一个回调函数 `X509TrustManager`,用于验证服务器证书是否合法。
在回调函数中,可以通过以下步骤来判断目标服务器证书颁发者机构是否合法:
1. 通过 `X509Certificate.getIssuerDN()` 方法获取服务器证书颁发者的 DN(Distinguished Name)。
2. 将 DN 与可信任的证书颁发机构的 DN 进行比较,判断颁发者是否为可信任机构。
3. 如果颁发者是可信任机构,则调用 `X509TrustManager.checkValidity()` 方法检查证书是否过期。
以下是一个示例代码:
```
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(getSslSocketFactory());
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
for (X509Certificate cert : xcs) {
String issuerDN = cert.getIssuerDN().getName();
boolean trusted = isTrustedIssuer(issuerDN); // 判断颁发者是否为可信任机构
if (!trusted) {
throw new CertificateException("Untrusted certificate issuer");
}
cert.checkValidity(); // 检查证书是否过期
}
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
conn.setHostnameVerifier((s, sslSession) -> true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
private boolean isTrustedIssuer(String issuerDN) {
// 判断颁发者是否为可信任机构的逻辑
// 返回 true 表示颁发者是可信任机构,否则返回 false
}
```
在 `isTrustedIssuer()` 方法中,可以根据实际情况编写判断颁发者是否为可信任机构的逻辑。可以将可信任机构的 DN 存储在配置文件或数据库中,并在方法中读取并进行比较。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)