How to protect an API key in a .NET application

2.2k Views Asked by At

My application hits a number of web services, such as Twitter and Flickr. It uses API keys from those services, and I'd like to obfuscate them in my binaries. (I'm not really worried about piracy or anything, I just need to keep these keys secret.)

What's the best way to go about it?

If I store them as const SecureString, does that keep them out of memory? The MSDN description says the text is "deleted from computer memory when no longer needed", but isn't a const always in memory?

Will Dotfuscator obscure it in my assembly? (Assuming I can get it to work.)

3

There are 3 best solutions below

0
On

Anon is correct, there is no way to completely protect data; someone can always get it at.

But you want to make it as difficult as possible. This means not doing the things that make it easy to read:

  • not storing in a registry key (e.g. TwitterAPIKey REG_SZ)
  • not storing in a text file (e.g. twitterkey.txt), or in an ini file
  • not storing in the application's .config file
  • not storing as plain text in the binary
  • not storing unencrypted in the binary

This will leave people who have to have knowledge of a debugger, and (possibly) assembly code.

You've reduced the attack surface a lot.

Follow just the first three suggestions and you'll well on your way.

1
On

I've recently had to deal with exactly this situation. The problem isn't so much making sure someone can't easily find it using a hex editor but rather when it's sent over the wire to the various APIs. Simply running fiddler and watching requests will show the key regardless. Some APIs will have the benefit of a private/public key which helps a little.

The only solution I could come up with was to create a webservice of my own externally hosted that acted as a proxy between the client and the targeted API. This allowed me to generate individual keys to each terminal that I could activate/deactivate and majority of the sensitive data was stored on my remote proxy application.

Good luck!

~ "Dont't forget to drink your Ovaltine"

1
On

maybe you can ask your user to use their own api keys. They can register themselves to the apis, and then reference their key in your app's settings