douzai8285 2014-08-21 16:47
浏览 105
已采纳

如何使用md5生成随机令牌

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

  • 写回答

2条回答 默认 最新

  • dongzhan7253 2014-08-21 16:54
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding