Alduno
Alduno

Reputation: 307

How to add a server’s certificate to the client in Java / Android Studio

I am trying to connect to an SSL-Server implemented in Python from an Android phone. I self-signed a certificate server.crt and want to use this certificate inside the Android App.

How do I do this in Java? In Python this can be done in the following way:

sock = socket.socket(socket.AF_INET6)
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile = 'server.crt')
conn = context.wrap_socket(sock, server_hostname = HOST)
conn.connect((HOST, PORT))

My current Java code looks like this:

SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) factory.createSocket(HOST, PORT);

How can I extend this such that it uses the certificate? Thanks in advance!

Upvotes: 0

Views: 1255

Answers (1)

Kyle
Kyle

Reputation: 4298

Java by default uses a cacerts file which is where trusted certificate authorities are stored. This is located at jre/lib/security/cacerts. You can just add it there. Also, you can specify a different CA store via the Java cryptography options.

If you want to do it in code, you can. But this isn't really the right way to do it IMO. Implement the interface X509TrustManager. Then something like this:

X509TrustManager[] arr = new YourX509TrustManager []{new YourTrustManager()};
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), arr, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

Upvotes: 2

Related Questions