用Golang?生成6位验证码

aor9mmx1  于 2023-02-10  发布在  Go
关注(0)|答案(6)|浏览(616)

生成6位数代码的电话验证,下面是一个非常简单的方法,我用过

package main

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

var randowCodes = [...]byte{
    '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
}        

func main() {
    var r *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()))

    for i := 0; i < 3; i++ {
        var pwd []byte = make([]byte, 6)

        for j := 0; j < 6; j++ {
            index := r.Int() % len(randowCodes)

            pwd[j] = randowCodes[index]
        }

        fmt.Printf("%s\n", string(pwd))                                                                  
    }    
}

你有更好的办法吗?

zsbz8rwp

zsbz8rwp1#

您可以使用"crypto/rand"软件包:其实现加密安全的伪随机数发生器。(在The Go Playground上尝试):

package main

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

func main() {
    for i := 0; i < 3; i++ {
        fmt.Println(EncodeToString(6))
    }
}

func EncodeToString(max int) string {
    b := make([]byte, max)
    n, err := io.ReadAtLeast(rand.Reader, b, max)
    if n != max {
        panic(err)
    }
    for i := 0; i < len(b); i++ {
        b[i] = table[int(b[i])%len(table)]
    }
    return string(b)
}

var table = [...]byte{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}

输出:

640166
195174
221966

请参见:How to generate a random string of a fixed length in golang?

jm2pwxwz

jm2pwxwz2#

我已经派生了user6169399的答案,使用带有常量字符串和小修改的crypto/rand,结果如下:

import (
    "crypto/rand"
)

const otpChars = "1234567890"

func GenerateOTP(length int) (string, error) {
    buffer := make([]byte, length)
    _, err := rand.Read(buffer)
    if err != nil {
        return "", err
    }

    otpCharsLength := len(otpChars)
    for i := 0; i < length; i++ {
        buffer[i] = otpChars[int(buffer[i])%otpCharsLength]
    }

    return string(buffer), nil
}
62o28rlo

62o28rlo3#

我认为这是最简单的方法:

// generate new recovery code
t := fmt.Sprint(time.Now().Nanosecond())

fmt.Println(t[:6])

输出:

524339
743142
243470

功能用途:

func GenerateCode() string {
    return fmt.Sprint(time.Now().Nanosecond())[:6]
}

输出:

302663
477258
678557
jobtbby3

jobtbby34#

您还可以使用crypto/rand中的rand.Int()来生成随机性

import (
    "crypto/rand"
)

func GenerateOTPCode(length int) (string, error) {
    seed := "012345679"
    byteSlice := make([]byte, length)

    for i := 0; i < length; i++ {
        max := big.NewInt(int64(len(seed)))
        num, err := rand.Int(rand.Reader, max)
        if err != nil {
            return "", err
        }

        byteSlice[i] = seed[num.Int64()]
    }

    return string(byteSlice), nil
}
jxct1oxe

jxct1oxe5#

1.使用数学/兰德数:

func genCaptchaCode() string {
    r := rand.New(rand.NewSource(time.Now().UnixNano()))

    var codes [6]byte
    for i := 0; i < 6; i++ {
        codes[i] = uint8(48 + r.Intn(10))
    }

    return string(codes[:])
}

1.使用加密/兰德(更安全):

func genCaptchaCode() (string, error) {
    codes := make([]byte, 6)
    if _, err := rand.Read(codes); err != nil {
        return "", err
    }

    for i := 0; i < 6; i++ {
        codes[i] = uint8(48 + (codes[i] % 10))
    }

    return string(codes), nil
}
h7appiyu

h7appiyu6#

我需要一个更简单、更扁平的解决方案,所以我想出了这个

// Since Go 1.20 rand.Seed() deprecated

rand.New(rand.NewSource(time.Now().UnixNano()))

// generates a random number in the range of [0, 900000)
// We add 100000 to the result to ensure the minimum value is 100000
r := rand.Intn(900000) + 100000

fmt.Println(r)

旁注:rand.Intn(900000)不会生成900000,最大数量为899999,因此代码不会生成1,000,000

相关问题