If you’re working on a Android project that’s more than just Hello World, chances are you’ll need to add some secrets/tokens/API keys to your project. For example, you need to use Google Maps in your app to display the closest cat caffe to the user, in order for your app to use the maps SDK you must get a key that will authenticate your app to Google Maps so that they can charge you based on your usage of the maps SDK. If someone gets a hold of your key, they’ll get free access to Google Maps and you’ll get a huge bill to pay. For obvious reasons you’ll want to keep that key a secret. In this post we’re going to talk about some of the dos and don’ts on how to handle those secrets.
The easiest way to add a secret to your code is to just put it there and be done with it. That’s also the worst thing to do for several reasons.
We can extract all our secrets, even constants from our code and put them in our
file. This will bring them all under one roof AND we can use the flavors to provide different values based on our needs, paid/free or staging/production.
Then we can use them in our java code
or in our
We can take it even further and extract the values from the
file into a separate file so that we don’t clutter our build script.
We got everything in one place but we’re still committing them to our SCM. This is not ideal since someone can get access to them. The SCM can get hacked or something else can happen, in general it’s not a good practice to commit them.
We can add the file containing the secrets to
and only have it locally, but then when someone needs the keys you have to find a way to give it to them in a safe manner or something can happen to your dev machine and all secrets can be lost.
So what should we do? We should commit them to our SCM.
“Wait… Didn’t you just… told us not to?” Astute observation reader, yes I did, we’re going to commit them BUT we’re also going to encrypt them, that way we’ll have them in our SCM and no none can access them, not even us if we lose the password.
For encryption we’re going to use 256-bit AES encryption with Cipher Block Chaining (CBC) which is more than enough for us. At least until quantum computing becomes a thing.
And now we can be sure that our secrets are all in one place, safe and sound and ready to commit. We can store our encryption password in 1Password or KeePass for safekeeping/sharing with the team, we can create an alias for the commands above so that we don’t have to type them.
And that’s about it.
This is just one way to go about, if you have different/better ways I’ll be happy to know about them.