Last Updated: September 09, 2019
·
2.809K
· florianmski

Handle private keys in your android open source projects

Sometime you don't want to share a private key.
In those case, people who fork your work will have errors or have to tweak your code to get it work.
Instead, put your key in a file and put this file in the assets folder of your project.

Add this line to your .gitignore

assets/myprivatekey.txt

Then use this code to retrieve the key

try
{
    InputStream inputStream = getAssets().open("myprivatekey.txt");
    String key = Utils.readInputStream(inputStream).trim();
    //do whatever with your key
}
catch (IOException e)
{
    //log your error if the key is not mandatory
    //or let it crash with an explanation for 
    //the person who fork your project
    Log.d("TAG", "No keyfile found, you should blabla");
}

public static String readInputStream(InputStream in) throws IOException
{
    StringBuffer stream = new StringBuffer();
    byte[] b = new byte[4096];
    for (int n; (n = in.read(b)) != -1;)
        stream.append(new String(b, 0, n));

    return stream.toString();
}

See a real exemple in one of my project : https://github.com/florianmski/Coderwall-Android/blob/master/coderwall/src/com/florianmski/coderwall/CWApplication.java

I use bugsense and don't want people to use my key if they fork my project, as explained below I will receive strange bug reports that have nothing to do with my code.

This pro tip is vastly based on this link http://blog.bugsense.com/post/16981766100/handling-api-keys-in-an-open-source-android-project