问题描述
对于RESTful后端API,我想生成唯一网址令牌,以用于验证用户身份.
For a RESTful backend API, I want to generate unique url tokens to be used to authenticate users.
注册时提供的用于生成令牌的唯一数据是电子邮件地址.但是在生成令牌并将其发送给用户之后,我不需要解密收到的令牌即可获取电子邮件或其他信息.因此加密可以是单向的.
The unique data provided at registration to generate tokens are email addresses. But after generating tokens and sending that to the users, I don't need to decrypt received tokens to get email or other information. So the encryption can be one-way.
最初,我使用bcrypt这样做:
Initially I used bcrypt to do so:
func GenerateToken(email string) string {
hash, err := bcrypt.GenerateFromPassword([]byte(email), bcrypt.DefaultCost)
if err != nil {
log.Fatal(err)
}
fmt.Println("Hash to store:", string(hash))
return string(hash)
}
但是由于令牌是作为url参数提供的(例如/api/path/to/{token}
),所以我不能使用 bcrypt ,因为它会生成包含/
的令牌,如下所示:
But since the tokens come as a url parameter (like /api/path/to/{token}
) I can not use bcrypt because it generates tokens containing /
like this:
"$ 2a $ 10 $ NebCQ8BD7xOa82nkzRGA9OEh./zhBOPcuV98vpOKBKK6ZTFuHtqlK"
这将中断路由.
所以我想知道基于Golang中的电子邮件生成一些唯一的16-32个字符的字母数字令牌的最佳方法是什么?
So I'm wondering what is the best way to generate some unique 16-32 character alphanumeric tokens based on emails in Golang?
推荐答案
如前所述,您做错了,这是非常不安全的.
As it was already mentioned you are doing it wrong and this is super insecure.
- 使用加密软件包生成安全令牌.此令牌是完全随机的,不与任何电子邮件关联.
func GenerateSecureToken(length int) string {
b := make([]byte, length)
if _, err := rand.Read(b); err != nil {
return ""
}
return hex.EncodeToString(b)
}
- 创建将该令牌映射到用户标识符并在API请求期间对其进行验证的数据库表.
这篇关于如何在Golang中生成唯一的随机字母数字标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!