mirror of
				https://github.com/go-gitea/gitea.git
				synced 2025-10-31 19:06:18 +01:00 
			
		
		
		
	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:
		| @@ -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 | ||||
| } | ||||
|   | ||||
		Reference in New Issue
	
	Block a user