生成用于电话验证的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))
}
}
你有更好的方法吗?
答案 0 :(得分:5)
您可以使用“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?
答案 1 :(得分:3)
我通过使用crypto/rand
和const字符串并进行了一些小的修改来分叉user6169399的答案,结果是:
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
}