Answer the question
In order to leave comments, you need to log in
How to add self-signed certificate for SSL connection?
Good day. I'm trying to set up an SSL connection to my server using a self-signed certificate.
But I can't add my certificate to TrustManager, I get an error:
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.
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;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question