1
0
Fork 0
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:
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

@ -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
}