Month: August 2016

Android Certificate Pinning


Securing your web sites and services using HTTPS is something you should be doing no matter what. Last year the government mandated all their sites move to HTTPS, and even Google is rewarding secure sites in its ranking algorithm. There is no reason for not using HTTPS any more. Since HTTPS is the baseline for web apps, certificate pinning should be the baseline for mobile apps interacting with the web.

OWASP published a good description of certificate pinning. To summarize, pinning a certificate means that your app is verifying that the site the app is communicating with is the actual site by comparing the certificate presented by the site to one bundled in the app. This prevents a man-in-the-middle attack on your app.

Why is this important to your app? It matters greatly if you also own the web service API or use a proprietary or paid API. Attackers can use a man-in-the-middle attack to reverse-engineer the web service interface, or to inject malicious data into the payload sent by your app to the web service. In fact, I have used this technique in the past to deconstruct a vendor’s API to better understand how to call it. Lucky for me (but bad for consumers) that they didn’t pin certificates in their Android app in the Play Store.

How Do I Pin a Certificate?

Get the Certificate

First, you must acquire the certificate. Luckily you only need the certificate, and not the private key. If your team/company built the web services, you can get the certificate from them. If you are consuming a public API, there are a variety of ways to get the certificate. I just use OpenSSL from the command line:

ex +'g/BEGIN CERTIFICATE/,/END CERTIFICATE/p' <(echo | openssl s_client -showcerts -connect -scq > export.crt

In all likelihood, there will be more than one certificate found by that command, known as the certificate chain. You need the whole chain, and the above command will place those into the file. This file will be placed into the Java keystore.

Create the Keystore

You will need to download the BouncyCastle jar which is a cryptography API we’ll use to convert the certificate into the required .bks keystore. Create the keystore from the command line:

keytool -importcert -v -trustcacerts -file export.crt -alias ca -keystore pin.bks -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath /path/to/bcprov-jdk15on-155.jar -storetype BKS -storepass thekeystorepassword

Move the resulting .bks file into the res/raw folder of your Android Studio project.

Using the Keystore in Code

To keep the example simpler, we’ll look at how to use it directly with the HttpsURLConnection object. We’ll open the keystore, set its contents to an SSLContext, and then add a TrustManagerFactory to the SSLContext. Finally, we’ll associate the SSLContext object to the HttpsURLConnection and then the code can proceed as normal from there.

KeyStore trusted = KeyStore.getInstance("BKS");
InputStream store = app.getResources().openRawResource(;
trusted.load(store, "thekeystorepassword");
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

final URL networkUrl = new URL("");
final HttpsURLConnection conn = (HttpsURLConnection) networkUrl.openConnection();

final InputStream inputFromServer = conn.getInputStream();

But I Use Retrofit!

(updated 4-19-2017)

Retrofit and the OkHttpClient make it even easier. You don’t need the certificate in a keystore. All you need is a hash of the public key, which you can get using this command:

openssl s_client -connect | openssl x509 -pubkey -noout | openssl rsa -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64

In your Android code you use the CertificatePinner object and inject that into the OkHTTPClient builder before building your Retrofit object. Note the prepending of the hash type and a slash before the actual hash value:

CertificatePinner certificatePinner = new CertificatePinner.Builder()
    .add("", "sha256/UXRFPJGwFvvyJI3vFOMIc19r0JNlNSQydEnYRrZI/W4=")
client = httpClient.certificatePinner(certificatePinner).build();

builder = new Retrofit.Builder()


So some of you may be thinking:

Hey, hold on there. The certificate (and keystore password) is in my app now. Can’t someone decompile the app and get the certificate?

Yep, that’s true, someone could get the certificate (unless you used Retrofit), which they can technically fetch even without your app. The good news is that they can’t use the certificate to fake being the web server without the private key, which we never used here or included in the keystore. The certificate is publicly available, you aren’t decreasing the security of your app, you are increasing it!

Also, I’d like to point out that I didn’t use the term SSL. At this point in time, well-hardened web servers shouldn’t be using SSL, they are actually using TLS. SSL has become synonymous with HTTPS and that’s just wrong, and even SSL vs TLS is not a completely equitable comparison. HTTPS means the connection is secure, SSL or TLS is the method used to secure the connection.

First Time Jenkins iOS Build Stalls

We’ve been adding some Cordova-based builds into our system, and the first iOS build kept stalling during the build. After some troubleshooting and Googling I came across this fantastic article: Automating Cordova Workflow: xcodebuild Hangs During iOS Build. What Simon describes is exactly the effect we were observing, and his solution solved the problem. What is happening is Cordova is not creating the Xcode project correctly, it’s missing the schemes. Opening Xcode on the server fixes this, as does the scripted solution presented by Simon.

But even better than fixing our current problem with Cordova, one of the commenters solved another mystery which I’ve encountered for a long time in Jenkins iOS builds. The first time a project is built using Jenkins, it never seems to work. But if you remote into the server and just open the project using Xcode, it magically starts working after that. Turns out the schemes are stored in xcuserdata, which we are keeping out of source control with .gitignore. Opening the IDE on the server causes the schemes to be created. The real solution is to set the schemes to shared in Xcode. Open the Product menu in Xcode, choose Scheme then Edit Scheme:

Xcode Edit Scheme Window with Shared checked
Click the Shared checkbox then check in the project. The schemes will now be part of the build and it won’t hang mysteriously any more.

Work Kudos

My team helped develop a demonstration Real-Time Health System described in this article.  It was a fun project using lots of different technologies:

  • Android
  • iOS
  • Spring/Java REST Services
  • iBeacon
  • Vertica
  • AWS

My team built the mobile apps that interacted with iBeacons to simulate the interactions described in the article, both Android and iOS published in their respective stores. We also built middleware, REST-based web services and the actual disease model that ran the simulation. These communicated to a Vertica back-end where another team performed analytics on the data.

The demo ran at four conferences, including HIMSS in both 2015 and 2016.


I had been considering re-launching my blog for a while now and wanted to get back into the rhythm of writing regularly. I recently discovered John Sonmez at Simple Programmer and was impressed by his content. Listening to him has motivated me to move ahead and get blogging again.

John offers an email-based blogging course, and although I am a long-time blogger I found real value in what the course taught. Because I have blogged for a while, I have definitely seen many of the effects he describes, so I believe in what John is teaching. I feel I could do better, and his course has given me more techniques and inspiration to get more out of my blogging effort. I’m glad I spent the time on his course. Check out his YouTube videos too, there is a ton of good content.

New Mobile Blog

I’ve decided to re-launch my blog under a different header as I am primarily writing about mobility now. My old blog content is mostly .Net-related, and I’m not really working in that space any more. It makes sense to me to curate the content differently.

The reason I blog is that I find so many great answers to questions and tutorials on how to do things, and I feel compelled to do my part (as I have since I started blogging in 2003). Welcome, and I hope you find something useful.