diff options
Diffstat (limited to 'modules')
-rw-r--r-- | modules/base/tool.go | 32 |
1 files changed, 23 insertions, 9 deletions
diff --git a/modules/base/tool.go b/modules/base/tool.go index f42c8b85..198ef9d1 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -15,6 +15,7 @@ import ( "hash" "html/template" "math" + "math/big" "net/http" "strings" "time" @@ -82,18 +83,31 @@ func BasicAuthEncode(username, password string) string { } // GetRandomString generate random string by specify chars. -func GetRandomString(n int, alphabets ...byte) string { +func GetRandomString(n int) (string, error) { const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - var bytes = make([]byte, n) - rand.Read(bytes) - for i, b := range bytes { - if len(alphabets) == 0 { - bytes[i] = alphanum[b%byte(len(alphanum))] - } else { - bytes[i] = alphabets[b%byte(len(alphabets))] + + 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) { + rand, err := rand.Int(rand.Reader, max) + if err != nil { + return 0, err } - return string(bytes) + + return int(rand.Int64()), nil } // http://code.google.com/p/go/source/browse/pbkdf2/pbkdf2.go?repo=crypto |