Поскольку я нигде не могу найти хорошего примера в Интернете, вот мое универсальное решение проблемы.Используйте набор корневых сертификатов, хранящихся ВНУТРИ файла jar, и разархивируйте их во время выполнения.Затем используйте сертификаты в диспетчере доверия, заменив старые Java.Закрепление сертификатов является приемлемым решением, если вы хотите подключиться только к одному серверу, однако это решение должно охватывать большую часть Интернета.Вам нужно откуда-то получить корневые сертификаты, я использовал хранилище Windows Trust для экспорта сертификатов в кодировке 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('!')));
}
}
Приведенный выше код обрабатывает создание массива TrustManager [], который можно использоватьв соединениях HTTPS следующим образом:
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 "";
}