Pages

Sunday, September 25, 2016

How To Hide Keys in Android


Android apps which make RESTful calls typically need to supply an api key when making HTTP requests. Ideally, you wanna create an Android app that uses Twitter APIs, so yo need an API key and an API secrets only you and your apps know. Because you need these values inside you app, it’s easy and quick to write them down directly in your source code. But when you commit this code to GitHub (or any other public repo), practically you’re telling your secret keys to entire world. Seems uncommon??

For example, if you declare in code

private static final String API_KEY = “123456abc”;
private static final String API_URL = “https://your-domain-api.com/api/”;

and push your changes to a public git repo, your api key is now known to everyone. Other developers could re-use it.

One simple way to avoid this bad practice is to store your values inside an environmental variable, so only your machine knows it, then read this values in some way and inject them in your code at build time. For best way where i can find is hiding your keys inside gradle.properties

Where to find gradle.properties
  1. Show Hidden files
  2. Find .gradle folder in ~/Users and Click it
  3. You will find gradle.properties file inside .gradle folder. If not exist, then create new file name gradle.properties
  4. Then store anything that you want inside it. See below example:

Note (Warning): 
  1. Amend your .gitignore file to exclude gradle.properties from version control /gradle.properties
  2. Remove your gradle.properties file from your remote git repo, if it exists.

How to use the .gradle.properties global variable

Just call the name inside the build.gradle

for example:

signingConfigs {


    release {

        storeFile file('../yourkeystore.keystore')

        storePassword PROJECT_STORE_PASSWORD

        keyAlias PROJECT_KEY_ALIAS

        keyPassword PROJECT_KEY_PASSWORD

    }


    debug{



    }

}

buildConfigField 'String','SECRETKEY',PROJECT_API_SECRET
buildConfigField 'String','URL_API',PROJECT_URL_API_DEBUG

Then if you want to call the buildConfigField inside your code : BuildConfig.URL_API to get the value in gradle.properites



That’s all, then it’s up to you how to create more elaborated configurations. 

No comments:

Post a Comment