Using a pinned certificate for SSL communication

Using a pinned certificate for SSL communication can enhance security when communicating to a known service. The certificate from the server can be hard coded into a client application and used during SSL verification as an additional check. This has the drawback of requiring a client application update prior to the server certificate expiration.

The following example uses Apache HTTPClient and overrides the default TrustStrategy. There is no specific reason for using Apache HTTPClient in this example so feel free to use your favorite client.

This example will use the certificate method of pinning, but be aware there are other techniques such as public key pinning.

First we will load the certificate file from the classpath. The project will need the certificate file packaged into the .jar file and available in the classpath. For this example, server.cert was obtained from the server and saved into a maven based project under src/main/resources

Next we use a custom TrustStrategy as a verification example. This will not perform SSL validation and is intended as an example only. Do not copy and paste this code into a production application without adding validation.

The code will generate a thumbprint of both the SSL cert found on the server, and the local cert embedded into the jar file. These thumbprints are compared and accepted if they match.