Protecting Your Api Keys


When the app will be released and distributed, those keys will need to be included in the app somehow. Once the keys are out there they can not be 100% protected from a determined mind. So, why bother? Why would I want to hide the api keys in the source code? Here are some good reasons

1. It might be illegal to put the keys out there in plain sight for the whole world to see.
2. Developer keys may be throttled or have other restrictions on how many times they can be used per day or per minute.
3. The keys might allow access to expensive cloud computing resources.
4. The keys might allow access to confidential/sensitive customer data.

First, I had to take my keys back from git repo. Can you really remove information from a public git repository? Yes, you can, using git filter-branch. Here is how – It worked! I successfully rewrote the history! My past commits don’t have those file(s) anymore that had my private api keys.

Next, I made sure that I don’t make this mistake again –

1. I added a new file ApiKeys.cs to the project.
2. Exposed the api keys as constants from a static class in this new file.
3 Added ApiKeys.cs in .gitignore file, to prevent this file from being committed to the repository.
4. Added instructions in ReadMe.txt for external developers to include their own keys.

This is not an ideal solution. If you are using a continuous build server, this technique will obviously not work. The code will not compile as-is, a file must be added to the project before it will start compiling. This works for me for now, but I am still looking for a better solution.

2 thoughts on “Protecting Your Api Keys

  1. Why not create a partial class comprised of two files and git ignore only the one with the sensitive data? Something like:

    public static partial class ApiKeys
    private static string privateKey = “99999”;
    public static partial class ApiKeys
    private static string publicKey = “12345”;
    public static string ApiKey
    var fields = typeof(ApiKeys).GetFields(BindingFlags.NonPublic | BindingFlags.Static);
    var privateKeyField = fields.SingleOrDefault(p => p.Name.Equals(“privateKey”));
    return (privateKeyField != null) ? privateKeyField.GetValue(null).ToString() : publicKey;

Leave a Reply
