我正在编写一个桌面应用程序,需要从我的仅 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 valid certification path to requested target
我尝试了很多解决方案,这似乎是最接近我的问题的:
尽管 Verisign 证书有效,但“PKIX 路径构建失败”
不幸的是,我的服务器没有出现任何问题,并且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 信任存储导出 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 和 Let's Encrypt SSL 证书时遇到了麻烦,在检查了 Java 版本与 Let's Encrypt 的兼容性后,我发现我的 API Web 服务器不提供完整的链,而只提供单个证书。
使用全链证书更改网络服务器设置,错误已解决。