Skip to content

Generate License Key #80

@openHacking

Description

@openHacking

golang写一个生成license key的函数,有以下要求

  1. character map: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
  2. Number of chunks:4
  3. Chunk length:5
  4. Separator:-
  5. 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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions