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>
This commit is contained in:
silverwind 2021-05-10 08:45:17 +02:00 committed by GitHub
parent 270aab429e
commit 1e6fa57acb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 100 additions and 192 deletions

View file

@ -6,7 +6,9 @@ package util
import (
"bytes"
"crypto/rand"
"errors"
"math/big"
"strings"
)
@ -124,3 +126,28 @@ func MergeInto(dict map[string]interface{}, values ...interface{}) (map[string]i
return dict, nil
}
// RandomInt returns a random integer between 0 and limit, inclusive
func RandomInt(limit int64) (int64, error) {
int, err := rand.Int(rand.Reader, big.NewInt(limit))
if err != nil {
return 0, err
}
return int.Int64(), nil
}
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// RandomString generates a random alphanumerical string
func RandomString(length int64) (string, error) {
bytes := make([]byte, length)
limit := int64(len(letters))
for i := range bytes {
num, err := RandomInt(limit)
if err != nil {
return "", err
}
bytes[i] = letters[num]
}
return string(bytes), nil
}