如何使用MD5生成一个随机令牌

huangapple go评论85阅读模式
英文:

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 如何使用MD5生成一个随机令牌 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))
}

http://play.golang.org/p/mmAzXLIZML

答案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.

huangapple
  • 本文由 发表于 2014年8月22日 00:47:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/25431658.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定