随机字符串生成

This commit is contained in:
wolter 2024-05-08 11:13:57 +08:00
parent 461c734a6e
commit 8ce86e4621
2 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,37 @@
package encrypt
import (
"math/rand"
"unsafe"
)
const lettersString = "0123456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
// 字符串长度
const number = 16
/*
16位码前15位随机字符串最后一位通过前15位字符串计算校验生成
*/
func LotteryEncryptEncode() string {
b := make([]byte, number)
var sum byte
for i := 0; i < number-1; i++ {
b[i] = lettersString[rand.Int63()%int64(len(lettersString))]
sum += b[i]
}
b[number-1] = lettersString[sum%byte(len(lettersString))]
return *(*string)(unsafe.Pointer(&b))
}
func LotteryEncryptDecode(str string) bool {
var sum byte
for i := 0; i < len(str)-1; i++ {
sum += str[i]
}
if lettersString[sum%byte(len(lettersString))] != str[len(str)-1] {
return false
}
return true
}

View File

@ -0,0 +1,15 @@
package encrypt
import "testing"
func TestLotteryEncryptEncode(t *testing.T) {
code := LotteryEncryptEncode()
t.Log(code)
}
func TestLotteryEncryptDecode(t *testing.T) {
code := LotteryEncryptEncode()
t.Log(code)
result := LotteryEncryptDecode(code)
t.Log(result)
}