diff --git a/generate/generate.go b/generate/generate.go index b6cdbf8..4e7bff7 100644 --- a/generate/generate.go +++ b/generate/generate.go @@ -24,6 +24,25 @@ func GetRandomString(n int) (string, error) { return string(buffer), nil } +// GetRandomKey 取得隨機金鑰 +func GetRandomKey(n int) (string, error) { + const alphaNum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@#$%^&*()-_=+" + + buffer := make([]byte, n) + max := big.NewInt(int64(len(alphaNum))) + + for i := 0; i < n; i++ { + index, err := randomInt(max) + if err != nil { + return "", err + } + + buffer[i] = alphaNum[index] + } + + return string(buffer), nil +} + func randomInt(max *big.Int) (int, error) { random, err := rand.Int(rand.Reader, max) if err != nil {