Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate a random token with md5

Tags:

go

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

like image 391
Leahcim Avatar asked Aug 21 '14 16:08

Leahcim


2 Answers

uuid is annother chooice. see

go get  "code.google.com/p/go-uuid/uuid"

and the func uuid.New() is what you wanted.

like image 60
JessonChan Avatar answered Nov 12 '22 03:11

JessonChan


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)
}
like image 28
JimB Avatar answered Nov 12 '22 03:11

JimB