package generate import ( "crypto/rand" "fmt" ) // GetRandomString 取得隨機字串 func GetRandomString(n int) (string, error) { const alphaNum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" return getRandomFromCharset(n, alphaNum) } // GetRandomKey 取得隨機金鑰 func GetRandomKey(n int) (string, error) { const alphaNum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@#$%^&*()-_=+" return getRandomFromCharset(n, alphaNum) } // getRandomFromCharset 通用隨機字串生成器 func getRandomFromCharset(n int, charset string) (string, error) { // 預先計算字符集的長度 charsLen := len(charset) buffer := make([]byte, n) // 使用 crypto/rand 生成隨機數據 _, err := rand.Read(buffer) if err != nil { return "", fmt.Errorf("failed to generate random data: %w", err) } // 從字元集選擇字符 for i := 0; i < n; i++ { buffer[i] = charset[int(buffer[i])%charsLen] } return string(buffer), nil }