forked from forgejo/forgejo
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:
parent
270aab429e
commit
1e6fa57acb
15 changed files with 100 additions and 192 deletions
|
@ -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
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue