Доброго времени суток. Пытаюсь настроить SSL подключение к своему серверу по self-signed сертификату.
Но не получается добавить свой сертификат в TrustManager, получаю ошибку:
SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
Для обхода создал свой TrustManager, но мне не кажется это решение правильным.
static class MyTrustManger implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
public static SSLSocket createSSL() {
try {
KeyStore trustStore = KeyStore.getInstance("BKS");
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
InputStream trustStoreStream = context.getResources().openRawResource(R.raw.certstore);
trustStore.load(trustStoreStream, "1234".toCharArray());
trustManagerFactory.init(trustStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); //Не работает
// TrustManager[] trustManagers = new TrustManager[]{new MyTrustManger()}; //Работает
KeyStore keyStore = KeyStore.getInstance("BKS");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
InputStream keyStoreStream = context.getResources().openRawResource(R.raw.clientkeystore);
keyStore.load(keyStoreStream, "1234".toCharArray());
keyManagerFactory.init(keyStore, "1234".toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagers, new SecureRandom());
return (SSLSocket) sslContext.getSocketFactory().createSocket(host, 1443);
} catch (Exception e) {
return null;
}
}