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 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器