随机字符串生成
This commit is contained in:
parent
461c734a6e
commit
8ce86e4621
|
@ -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
|
||||
}
|
|
@ -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)
|
||||
}
|
Loading…
Reference in New Issue