From d96f2a71849ed312c3c69177f1cb7b4a174421da Mon Sep 17 00:00:00 2001 From: leonklingele Date: Wed, 21 Dec 2016 09:41:37 +0100 Subject: Fix random string generator (#3953) * Remove unused custom-alphabet feature of random string generator * Fix modulo-biased random string generator * Random string generator should return error if it fails to read random data via crypto/rand --- modules/base/tool.go | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) (limited to 'modules/base') 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 -- cgit v1.2.3