Search code examples
androidsslhttpscertificateokhttp

Enabling HTTPS communication between my server and my client


I have already built a server app and an android app. So far they were communicating over http, but I am sending sensitive information in each request (like JWT). Therefore I neet to use Https instead.

I have generated a p12 certificate.

On the server side:

  1. I've copied the certificate to resources/keystore/sampleName.p12
  2. I've added these lines to my application.properties

    server.ssl.key-store-type=PKCS12
    server.ssl.key-store-password=samplePassword
    server.ssl.key-store=classpath:keystore/sampleName.p12
    server.ssl.key-alias=sampleName
    

On android side I use okHttp and create the client like this

val httpClient = OkHttpClient.Builder()
    .certificatePinner(
        CertificatePinner.Builder()
            .add(
                https://10.0.2.2:8080,
                "sha256/lVIcG+gpmlabsq1bW5RbvB+kqVSHKdOFyoxjo9+SLEs="
            ).build()
    )
    .build()

I use https://10.0.2.2:8080 because I run the server app only localy and I also run the android app on an emulator on the same laptop.

To get sha256/lVIcG+gpmlabsq1bW5RbvB+kqVSHKdOFyoxjo9+SLEs= I've used keytool -list -v -keystore sampleName.p12 -storetype PKCS12 -storepass samplePassword and converted the sha256 fingerprint which was in hex to base64.

Now when I try to send any request to the server I get an

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

I am clearly missing something but I dont know what. Is there anything else I need to do? Or did I do something wrong? Or is it just not supposed to work localy?

Note that this is just an exercise for me and I won't be actually deploying the server app on any real server and I won't release the android app.

But still I will be presenting the solution and I really nedd it to be solid and work localy.


Solution

  • CertificatePinning is in addition to the normal certificate checks. It only further restricts the choice of certificate, since be default you will accept any cert for your host.

    See Adding a custom certificate to an OkHttp Client for an existing answer.

    Or read up here

    https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java

    https://square.github.io/okhttp/4.x/okhttp/okhttp3/-certificate-pinner/