Gracefully dealing with private keys in Kotlin MultiPlatform

Mustafa Ozhan
2 min readFeb 18, 2021

Yesterday I shared my KMP project with someone in order to give an example from it but building the project failed because that person didn’t have the secret keys. Then I realised that I didn’t give enough attention about how to host secrets so that others can easily clone and build the project successfully.

Aim

The aim is simple, I want to secure my keys! I don’t want to commit them but in the same time I don’t want my project to fail because of missing keys if a person clones it.

Before

When I started to move my project to KMP, I didn’t give much attention how to deal with this scenario. I created an object called Keys, I had const values in it and I added this file to .gitignore so that no one can see it. Then I added a step into my GitHub Action file in order to deal with CI:

BuildKonfig

Before I start, I want to share the library I use. It is called BuildKonfig. It is a great solution for KMP projects.

Android Developers familiar with BuildConfig class, it is an auto-generated class and we are able to pass values and keys from Gradle to Java/Kotlin files. BuildKonfig is doing same for Kotlin Multi Platform 💪

If you check the library, you will see that they use the simple approach:

It generates a com.example.app.BuildKonfig file with one String variable called name and the value is value

The problem here is that I still have to put my keys 🤔

They suggest to use it with gradle.properties like this:

and in gradle:

It looks great but it still doesn’t solve my problem. I have to commit gradle.properties since it is part of the build. So I started to look for a way that I can handle this without committing the file.

Solution

I decided to create a file and call it key.properties inside common module and I added it into my .gitignore

And I added into build.gradle.kts (common)

So by this way I kept key.properties in my local and I didn’t commit it and application build successfully since props["base_url_backend"] returned null. It passed http://fake.backend.url into BuildKonfig object.

Now the cloned project can be easily compiled with fake urls since we use asBuildKonfig.BASE_URL_API anywhere in app.

The final BuildKonfig object for people that cloned my repo will be:

And for me the values are the real ones, since I have key.properties in my local 🙂

If you want to check the commit regarding to these changes, it is here

Happy coding!

--

--