0

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!

1

1 Answer 1

2

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()); 
Sign up to request clarification or add additional context in comments.

4 Comments

Thank for the answer! But is it possible to deliver the certificate together with the app in Android if I use the first option?
Modifying the cacerts is always an indicator of bad application design (especially as it does not make much sense on Android as it requires root permissions). Therefore please stop suggesting it as the first solution! Also the posted code misses the relevant part where the trust store is loaded.
@Robert cacerts is the default location of JRE wide trusted certificate authorities. Therefore it is a perfectly valid location for putting trusted certificates. It is probably better for server side applications than Android applications if that is what you meant by bad app design. For server side applications, it's accepted practice.
And @MarkusK96, the way I would do it is to ship the cert with your application. Perhaps there is a directory for your app where the cert can be placed? I am not an Android developer, but that seems logical and would allow you to read in the cert and use the X509TrustManager. Since it'd be part of your app package, you wouldn't require root perms as Robert mentioned.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.