生成新 API 密钥的最佳方法是什么?

问题描述:

所以现在有很多不同的服务,Google API、Twitter API、Facebook API 等等.

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

每个服务都有一个 API 密钥,例如:

Each service has an API key, like:

AIzaSyClzfrOzB818x55FASHvX4JuGQciR9lv7q

所有密钥的长度和包含的字符各不相同,我想知道生成 API 密钥的最佳方法是什么?

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

我不是要求特定的语言,只是创建密钥的一般方法,它们应该是用户应用程序细节的加密,还是散列或随机字符串的散列等.我们是否应该担心关于哈希算法(MSD、SHA1、bcrypt)等?

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?

我和几个朋友(电子邮件/推特)谈过,他们建议只使用去掉破折号的 GUID.

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

不过这对我来说似乎有点hacky,希望能得到更多的想法.

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

使用专为密码学设计的随机数生成器.然后对数字进行 base-64 编码.

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

这是一个 C# 示例:

This is a C# example:

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