feat(subscribe): add short token generation and validation logic

This commit is contained in:
Chang lue Tsen
2025-11-18 12:03:14 -05:00
parent 8a4cfcbdb3
commit e3999ba75f
7 changed files with 86 additions and 1 deletions
+38
View File
@@ -0,0 +1,38 @@
package tool
import (
"crypto/sha256"
"encoding/binary"
"errors"
"math/rand"
)
func FixedUniqueString(s string, length int, alphabet string) (string, error) {
if alphabet == "" {
alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
}
if length <= 0 {
return "", errors.New("length must be > 0")
}
if length > len(alphabet) {
return "", errors.New("length greater than available unique characters")
}
// Generate deterministic seed from SHA256
hash := sha256.Sum256([]byte(s))
seed := int64(binary.LittleEndian.Uint64(hash[:8])) // 前 8 字节
r := rand.New(rand.NewSource(seed))
// Copy alphabet to mutable array
data := []rune(alphabet)
// Deterministic shuffle (FisherYates)
for i := len(data) - 1; i > 0; i-- {
j := r.Intn(i + 1)
data[i], data[j] = data[j], data[i]
}
// Take first N characters
return string(data[:length]), nil
}
+27
View File
@@ -0,0 +1,27 @@
package tool
import (
"testing"
)
func TestFixedUniqueString(t *testing.T) {
a := "example"
b := "example1"
c := "example"
strA1, err := FixedUniqueString(a, 8, "")
strB1, err := FixedUniqueString(b, 8, "")
strC1, err := FixedUniqueString(c, 8, "")
if err != nil {
t.Logf("Error: %v", err.Error())
return
}
if strA1 != strC1 {
t.Errorf("Expected strA1 and strC1 to be equal, got %s and %s", strA1, strC1)
}
if strA1 == strB1 {
t.Errorf("Expected strA1 and strB1 to be different, got %s and %s", strA1, strB1)
}
t.Logf("strA1 and strB1 are not equal, strA1: %s, strB1: %s", strA1, strB1)
t.Logf("strA1 and strC1 are equal,strA1: %s, strC1: %s", strA1, strC1)
}