diff options
author | silverwind <me@silverwind.io> | 2021-05-10 08:45:17 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-05-10 07:45:17 +0100 |
commit | 1e6fa57acbe3c05cb996b789e8c2d381c953826f (patch) | |
tree | c4f1ce55b3423f97952b630462cef5b2035961ec /modules/generate/generate.go | |
parent | 270aab429ef025df9a0b9bf9e3982729ae8df449 (diff) | |
download | gitea-1e6fa57acbe3c05cb996b789e8c2d381c953826f.tar.gz gitea-1e6fa57acbe3c05cb996b789e8c2d381c953826f.zip |
Use single shared random string generation function (#15741)
* Use single shared random string generation function
- Replace 3 functions that do the same with 1 shared one
- Use crypto/rand over math/rand for a stronger RNG
- Output only alphanumerical for URL compatibilty
Fixes: #15536
* use const string method
* Update modules/avatar/avatar.go
Co-authored-by: a1012112796 <1012112796@qq.com>
Co-authored-by: a1012112796 <1012112796@qq.com>
Diffstat (limited to 'modules/generate/generate.go')
-rw-r--r-- | modules/generate/generate.go | 32 |
1 files changed, 2 insertions, 30 deletions
diff --git a/modules/generate/generate.go b/modules/generate/generate.go index 304ad87f21..96589d3fb9 100644 --- a/modules/generate/generate.go +++ b/modules/generate/generate.go @@ -9,31 +9,12 @@ import ( "crypto/rand" "encoding/base64" "io" - "math/big" "time" + "code.gitea.io/gitea/modules/util" "github.com/dgrijalva/jwt-go" ) -// GetRandomString generate random string by specify chars. -func GetRandomString(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 -} - // NewInternalToken generate a new value intended to be used by INTERNAL_TOKEN. func NewInternalToken() (string, error) { secretBytes := make([]byte, 32) @@ -69,19 +50,10 @@ func NewJwtSecret() (string, error) { // NewSecretKey generate a new value intended to be used by SECRET_KEY. func NewSecretKey() (string, error) { - secretKey, err := GetRandomString(64) + secretKey, err := util.RandomString(64) if err != nil { return "", err } return secretKey, nil } - -func randomInt(max *big.Int) (int, error) { - rand, err := rand.Int(rand.Reader, max) - if err != nil { - return 0, err - } - - return int(rand.Int64()), nil -} |