What's the best approach for generating a new API key? Ask Question

What's the best approach for generating a new API key? Ask Question

So with lots of different services around now, Google APIs, Twitter API, Facebook API, etc etc.

Each service has an API key, like:

AIzaSyClzfrOzB818x55FASHvX4JuGQciR9lv7q

All the keys vary in length and the characters they contain, I'm wondering what the best approach is for generating an API key?

I'm not asking for a specific language, just the general approach to creating keys, should they be an encryption of details of the users app, or a hash, or a hash of a random string, etc. Should we worry about hash algorithm (MSD, SHA1, bcrypt) etc?

Edit: I've spoke to a few friends (email/twitter) and they recommended just using a GUID with the dashes stripped.

This seems a little hacky to me though, hoping to get some more ideas.

ベストアンサー1

Use a random number generator designed for cryptography. Then base-64 encode the number.

This is a C# example:

var key = new byte[32];
using (var generator = RandomNumberGenerator.Create())
    generator.GetBytes(key);
string apiKey = Convert.ToBase64String(key);

おすすめ記事