gpt4 book ai didi

java - PKIX 路径构建在 Java 7 中失败但在 Java 8 中失败 - 尽管拥有浏览器信任的 Let's Encrypt 证书但无法连接到我的 HTTPS 服务器

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:28 24 4
gpt4 key购买 nike

我正在编写一个桌面应用程序,它需要从我的仅 HTTPS 服务器下载一些配置文件,该服务器运行有效的 Let's Encrypt 证书,该证书在 Chrome 和 Firefox 以及 Java 8 中受信任。我希望该应用程序兼容尽可能,所以我将 Java 7 作为最低目标。在 Java 7 中,应用程序无法连接错误 Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find请求目标的有效证书路径

我已经尝试了很多解决方案,这似乎是最接近我的问题的:

"PKIX path building failed" despite valid Verisign certificate

不幸的是,我的服务器和 https://www.ssllabs.com/ssltest/analyze.html?d=baldeonline.com 没有任何问题显示 Java 7 应该连接。

我如何以编程方式使用不同的(或系统的)证书存储?显然,如果用户必须在他们的 Java 安装文件夹中四处寻找,那么这对用户来说是不友好的,所以我想对程序本身进行任何更改。

引发错误的函数:

        try {
URL obj = new URL(urlPointer);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");//I have also tries TLSv1 but no difference
sslContext.init(null, null, new SecureRandom());
con.setSSLSocketFactory(sslContext.getSocketFactory());
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = 0;
try {
responseCode = con.getResponseCode();
} catch (IOException e) {
}
System.out.println("POST Response Code : " + responseCode);

if (responseCode >= 400) {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getErrorStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}

} catch (IOException e) {
e.printStackTrace();
return "";
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
return "";
} catch (KeyManagementException e1) {
e1.printStackTrace();
return "";
}

}```

最佳答案

由于我似乎无法在网上的任何地方找到一个很好的例子,所以这里是我针对该问题的通用解决方案。使用存储在 jar 文件中的一堆根证书,并在运行时解压缩它们。然后在信任管理器中使用证书,替换旧的 Java 证书。如果您只想连接到一台服务器,证书固定只是一个可接受的解决方案,但是这个解决方案应该覆盖大部分互联网。您需要从某个地方获取根证书,我使用 Windows Trust store 导出 X.509 base64 编码证书。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

public class CertificateHandler {
public String thisJar = "";

public CertificateHandler() {
try {
thisJar = getJarFile().toString();
thisJar = thisJar.substring(6).replace("%20", " ");
} catch (IOException e) {
thisJar = "truststore.zip";
e.printStackTrace();
}
//truststore.zip is used in place of the jar file during development and isn't needed once the jar is exported
}

public static TrustManagerFactory buildTrustManagerFactory() {
try {
TrustManagerFactory trustManager = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
try {
KeyStore ks;
ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null);
File dir = new File(Launcher.launcherSafeDirectory + "truststore");
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
try {
InputStream is = new FileInputStream(child);
System.out.println("Trusting Certificate: "+child.getName().substring(0, child.getName().length() - 4));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate caCert = (X509Certificate)cf.generateCertificate(is);
ks.setCertificateEntry(child.getName().substring(0, child.getName().length() - 4), caCert);
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
}
}
trustManager.init(ks);
} catch (KeyStoreException | CertificateException | IOException | NoSuchAlgorithmException e1) {
e1.printStackTrace();
}

return trustManager;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}

public static TrustManager[] getTrustManagers() {
TrustManagerFactory trustManager = buildTrustManagerFactory();
return trustManager.getTrustManagers();
}

public void loadCertificates() {
try {
UnzipLib.unzipFolder(thisJar, "truststore", Launcher.launcherSafeDirectory + "truststore");
System.out.println("Extracted truststore to "+ Launcher.launcherSafeDirectory);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private File getJarFile() throws FileNotFoundException {
String path = Launcher.class.getResource(Launcher.class.getSimpleName() + ".class").getFile();
if(path.startsWith("/")) {
throw new FileNotFoundException("This is not a jar file: \n" + path);
}
path = ClassLoader.getSystemClassLoader().getResource(path).getFile();
return new File(path.substring(0, path.lastIndexOf('!')));
}
}

上面的代码处理创建可在 HTTPS 连接中使用的 TrustManager[] 数组,如下所示:

private static final String USER_AGENT = "Mozilla/5.0";

static String sendPOST(String POST_URL, String POST_PARAMS, TrustManager[] trustManagers) {
try {
URL obj = new URL(POST_URL);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, trustManagers, new SecureRandom());
con.setSSLSocketFactory(sslContext.getSocketFactory());
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("User-Agent", USER_AGENT);

// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = 0;

try {
//sendPOST("http://localhost", postParams);
responseCode = con.getResponseCode();
} catch (IOException e) {
}
System.out.println("POST Response Code : " + responseCode);

if (responseCode >= 400) {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getErrorStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}

} catch (KeyManagementException | NoSuchAlgorithmException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return "";
}

关于java - PKIX 路径构建在 Java 7 中失败但在 Java 8 中失败 - 尽管拥有浏览器信任的 Let's Encrypt 证书但无法连接到我的 HTTPS 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56635216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com