diff options
author | leonklingele <git@leonklingele.de> | 2016-12-21 09:41:37 +0100 |
---|---|---|
committer | 无闻 <u@gogs.io> | 2016-12-21 03:41:37 -0500 |
commit | d96f2a71849ed312c3c69177f1cb7b4a174421da (patch) | |
tree | 8d68aa9631801722ecaeab3d2089bb2a922794b6 /modules/base | |
parent | adcb1d7c651720d71efea238e011582b9e455c2d (diff) |
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
Diffstat (limited to 'modules/base')
-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 |