Как проверить корректность SSL-сертификата в Java?
Есть код на Java, в котором я обращаюсь к стороннему серверу, отправляю туда POST-запрос и получаю в ответ JSON. В общих чертах код выглядит так:
// operationName - REST-операция на сервере, к которой я обращаюсь
// requestParams - запрос с серверу в JSON-формате (здесь описание того, что именно нужно вернуть)
final StringBuilder content = new StringBuilder();
final URL url = new URL(SERVICE_HOST + SERVICE_ENDPOINT + operationName + "/?lang=rus");
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setReadTimeout(CONNECTION_TIMEOUT);
connection.setUseCaches(false);
connection.setDoOutput(true);
final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(requestParams);
outputStream.flush();
outputStream.close();
try (
final InputStream inputStream = connection.getInputStream();
final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
final BufferedReader in = new BufferedReader(inputStreamReader);
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
} catch (final Exception ex) {
ex.printStackTrace();
}
Код предельно простой и делает то, что нужно.
Теперь я хочу изменить работу с внешним источником на работу через защищённый сокет (secured socket). В общих чертах логика работы понятна, не понятно, что должно быть в методе checkServerTrusted() TrustManager'а.
Есть цепочка сертификатов. Какие проверки необходимы и достаточны, чтобы проверить, что сертификат корректен и относится к сайту, к которому я обращаюсь?
Фрагмент кода из документации по JSSE (рус.):
* Delegate to the default trust manager.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
pkixTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException excep) {
/*
* Possibly pop up a dialog box asking whether to trust the
* cert chain.
*/
}
}
— здесь предполагается спрашивать юзера, доверять ли цепочке сертификатов. Интересно, как организовать проверку по-правильному, с рукопожатием и прочим.