生成API密钥的最佳方法[英] Best approach for generating API key

本文是小编为大家收集整理的关于生成API密钥的最佳方法的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

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

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

AIzaSyClzfrOzB818x55FASHvX4JuGQciR9lv7q

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

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

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

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

推荐答案

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

这是一个 C# 示例:

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

本文地址:https://www.itbaoku.cn/post/1937866.html

问题描述

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.

推荐答案

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);