英文:
how to generate a random token with md5
问题
我正在尝试生成一个随机令牌,用于实现重置密码功能。这是我第一次尝试的代码:http://play.golang.org/p/mmAzXLIZML。但是它并不像我希望的那样工作,因为它会一次又一次地生成相同的令牌(我猜这是由于时间不变)。我该如何生成一个使用md5算法的随机令牌,每次都会改变呢?
package main
import "fmt"
import "strconv"
import "time"
import "crypto/md5"
import "io"
func main() {
time := strconv.FormatInt(time.Now().Unix(), 10)
fmt.Println(time)
h := md5.New()
io.WriteString(h, time)
fmt.Printf("%x", h.Sum(nil))
}
链接:http://play.golang.org/p/mmAzXLIZML
英文:
I'm trying to generate a random token that I can use while implementing reset password functionality. This (http://play.golang.org/p/mmAzXLIZML) is the dazzling and non-functional code that I came up with for a first try. It doesn't work as I'd hope because it produces the same token over and over again (which I assume is a function of the time not changing). How do I generate a random token with md5 that will change every time?
package main
import "fmt"
import "strconv"
import "time"
import "crypto/md5"
import "io"
func main() {
time := strconv.FormatInt(time.Now().Unix(), 10)
fmt.Println(time)
h := md5.New()
io.WriteString(h, time)
fmt.Printf("%x", h.Sum(nil))
}
答案1
得分: 28
它之所以每次生成相同的结果,是因为它在游乐场中,时间被冻结,页面被缓存。
然而,这并不是一个好主意,因为根据请求的时间,可以猜测重置密码。
为什么必须使用md5?这里有一个随机令牌生成器:
func randToken() string {
b := make([]byte, 8)
rand.Read(b)
return fmt.Sprintf("%x", b)
}
请注意,以上代码是用Go语言编写的。
英文:
It generates the same result each time only because it's in the playground, where time is frozen and pages are cached.
This isn't a great idea though, since a reset password could be guessed based on the time the request was made.
Why does it have to be an md5? Here's a random token generator:
http://play.golang.org/p/3weHBU6YZr
func randToken() string {
b := make([]byte, 8)
rand.Read(b)
return fmt.Sprintf("%x", b)
}
答案2
得分: 1
uuid是另一个选择。请参考以下代码:
go get "code.google.com/p/go-uuid/uuid"
函数**uuid.New()**是你所需要的。
英文:
uuid is annother chooice. see
go get "code.google.com/p/go-uuid/uuid"
and the func uuid.New() is what you wanted.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论