From 8ce86e4621e0cc1b0bf871629b6f5b8f1a46bc62 Mon Sep 17 00:00:00 2001 From: wolter Date: Wed, 8 May 2024 11:13:57 +0800 Subject: [PATCH] =?UTF-8?q?=E9=9A=8F=E6=9C=BA=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?=E7=94=9F=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/utils/encrypt/encrypt.go | 37 +++++++++++++++++++++++++++++++ app/utils/encrypt/encrypt_test.go | 15 +++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 app/utils/encrypt/encrypt.go create mode 100644 app/utils/encrypt/encrypt_test.go diff --git a/app/utils/encrypt/encrypt.go b/app/utils/encrypt/encrypt.go new file mode 100644 index 0000000..e7e7efa --- /dev/null +++ b/app/utils/encrypt/encrypt.go @@ -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 +} diff --git a/app/utils/encrypt/encrypt_test.go b/app/utils/encrypt/encrypt_test.go new file mode 100644 index 0000000..90577ef --- /dev/null +++ b/app/utils/encrypt/encrypt_test.go @@ -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) +}