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))
}
http://play.golang.org/p/mmAzXLIZML
uuid is annother chooice. see
go get "code.google.com/p/go-uuid/uuid"
and the func uuid.New() is what you wanted.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With