美文网首页
go实现邮箱激活token

go实现邮箱激活token

作者: 苍老师的眼泪 | 来源:发表于2020-05-05 12:50 被阅读0次

实现要求:

  1. token必须独一无二,放在数据库索引列中
  2. token未被使用的情况下必须长期有效,所以token要有足够的安全性抵御暴力破解(cryptographically secure)
  3. token必须能放在url中
  4. token的长度相对固定

设计思路:

  1. token的唯一性用生成的uuid来保证
    https://golangnote.com/topic/177.html
    示例代码:
package main

 import (
    "crypto/rand"
    "fmt"
    "time"
 )

 func main() {
    // 生成32位的时间戳
    unix32bits := uint32(time.Now().UTC().Unix())

    buff := make([]byte, 12)

    numRead, err := rand.Read(buff)

    if numRead != len(buff) || err != nil {
        panic(err)
    }

    fmt.Printf("%x-%x-%x-%x-%x-%x", unix32bits, buff[0:2], buff[2:4], buff[4:6], buff[6:8], buff[8:])
 }
  1. 能否生成密码安全(cryptographically secure)的token需要系统的支持,如果系统不支持,直接panic让整个程序退出运行(硬伤,不然你还有别的办法不成?)
    https://gist.github.com/dopey/c69559607800d2f2f90b1b1ed4e550fb
    示例代码:
package main

import (
    "crypto/rand"
    "encoding/base64"
    "fmt"
    "io"
)

// Adapted from https://elithrar.github.io/article/generating-secure-random-numbers-crypto-rand/

func init() {
    assertAvailablePRNG()
}

func assertAvailablePRNG() {
        // 判断系统支不支持生成密码安全的(cryptographically secure)伪随机数
    buf := make([]byte, 1)

    _, err := io.ReadFull(rand.Reader, buf)
    if err != nil {
                //go所运行的系统不支持上述要求
        panic(fmt.Sprintf("crypto/rand is unavailable: Read() failed with %#v", err))
    }
}


func GenerateRandomBytes(n int) ([]byte, error) {
    b := make([]byte, n)
    _, err := rand.Read(b)
    // Note that err == nil only if we read len(b) bytes.
    if err != nil {
        return nil, err
    }

    return b, nil
}

// GenerateRandomString returns a securely generated random string.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func GenerateRandomString(n int) (string, error) {
    const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-"
    bytes, err := GenerateRandomBytes(n)
    if err != nil {
        return "", err
    }
    for i, b := range bytes {
        bytes[i] = letters[b%byte(len(letters))]
    }
    return string(bytes), nil
}


func GenerateRandomStringURLSafe(n int) (string, error) {
    b, err := GenerateRandomBytes(n)
    return base64.URLEncoding.EncodeToString(b), err
}

func main() {
    // 示例: 生成base64编码的44字节的token, 如果不能白为什么32字节进去,出来变成44字节建议先wiki一下base64
    token, err := GenerateRandomStringURLSafe(32)
    if err != nil {
        panic(err)
    }
    fmt.Println(token)

    // 示例: 生成32位的token
    token, err = GenerateRandomString(32)
    if err != nil {
        panic(err)
    }
    fmt.Println(token)
}

相关文章

网友评论

      本文标题:go实现邮箱激活token

      本文链接:https://www.haomeiwen.com/subject/nhkmghtx.html