-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
golang写一个生成license key的函数,有以下要求
- character map: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
- Number of chunks:4
- Chunk length:5
- Separator:-
- Prefix:user
package main
import (
"crypto/rand"
"fmt"
"strings"
)
// 生成License Key的函数
func GenerateLicenseKey(numChunks int, chunkLength int, separator string, prefix string) string {
charMap := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// 生成License Key的每个chunk
chunks := make([]string, numChunks)
for i := 0; i < numChunks; i++ {
chunk := make([]byte, chunkLength)
_, err := rand.Read(chunk)
if err != nil {
panic(err)
}
for j, b := range chunk {
chunk[j] = charMap[int(b)%len(charMap)]
}
chunks[i] = string(chunk)
}
// 拼接License Key
key := prefix
for i := 0; i < numChunks; i++ {
key += separator + chunks[i]
}
return key
}
func main() {
// 示例用法
licenseKey := GenerateLicenseKey(4, 5, "-", "user")
fmt.Println(licenseKey)
}这个函数使用Go的crypto/rand库生成随机的bytes,然后将其转换成License Key的字符集中的字符。每个chunk的长度为5个字符,License Key共有4个chunk,使用-作为分隔符,以user作为前缀。调用GenerateLicenseKey函数将返回一个新的License Key字符串。
Metadata
Metadata
Assignees
Labels
No labels