If you are a good developer you are securing your services with SSL encryption. Unless you have put in a lot of effort, local testing still uses the good old fashioned self signed certificate and just click through the warning window of shame.
This is great until you are writing a RESTful service to be consumed by something which isn’t a browser. If you are an Android developer you have probably come across blog posts (or the official Android docs) encouraging you to make your own Trust Manager to accept your certificate or, worse, disable certificate checking altogether! However, Android N has come to the rescue with new security configuration features.
Using Self Signed Certificates with Android N
To use a self signed certificate you need to
- Add a meta-data tag to your AndroidManifest.xml which points to a security configuration xml file
- Add to your xml resources directory the security configuration file
- Download your self signed certificate to your project
I’ve added in my projects the following code to Android Manifest’s application element
This code just informs Android that the configuration file is found in res/xml/network_security_config.xml.
Creating the Network Security Config
The full documentation for the network security files covers a lot more than our use case for a self signed certificate. It is well worth a read to understand what is being done.
Here is my XML file to load my certificate from the raw directory. I have it named server_aerogear_dev, but the file name is irrelevant. What matters is that the common name in the certificate file matches the domain name of the server. I am pretty sure that this also works with IP addresses, but I haven’t tested it.
<?xml version="1.0" encoding="utf-8"?>
Downloading the certificate
You can download the certificate to the raw directory in your source using your web browser or using the command line.
echo -n | openssl s_client -connect server.aerogear.dev:8443 | sed -ne ‘/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p’ > server_aerogear_dev
// Credit to SO : http://serverfault.com/questions/139728/how-to-download-the-ssl-certificate-from-a-website
Replace the name of the server and the port with configuration appropriate to you.
This is a very simple example of a new feature from Android N. This may change or go out of date. However, this gives us a simple was to manage security and it ALSO works within Android’s build flavor system. Take a look, and stay safe.