From da19700a1e39bdc8454ad1c357724278a812127c Mon Sep 17 00:00:00 2001 From: Tan Jiang Date: Tue, 25 Apr 2017 15:35:08 +0800 Subject: [PATCH] replace math/rand with crypto/rand --- src/common/utils/utils.go | 10 +++++++--- src/common/utils/utils_test.go | 4 ++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/common/utils/utils.go b/src/common/utils/utils.go index 89db42447..1ebdd5cfd 100644 --- a/src/common/utils/utils.go +++ b/src/common/utils/utils.go @@ -15,8 +15,8 @@ package utils import ( + "crypto/rand" "fmt" - "math/rand" "net" "net/url" "strings" @@ -65,11 +65,15 @@ func ParseRepository(repository string) (project, rest string) { // GenerateRandomString generates a random string func GenerateRandomString() string { length := 32 - rand.Seed(time.Now().UTC().UnixNano()) const chars = "abcdefghijklmnopqrstuvwxyz0123456789" + l := len(chars) result := make([]byte, length) + _, err := rand.Read(result) + if err != nil { + log.Warningf("Error reading random bytes: %v", err) + } for i := 0; i < length; i++ { - result[i] = chars[rand.Intn(len(chars))] + result[i] = chars[int(result[i])%l] } return string(result) } diff --git a/src/common/utils/utils_test.go b/src/common/utils/utils_test.go index 3a9b18cba..241ff72e3 100644 --- a/src/common/utils/utils_test.go +++ b/src/common/utils/utils_test.go @@ -140,6 +140,10 @@ func TestGenerateRandomString(t *testing.T) { if len(str) != 32 { t.Errorf("unexpected length: %d != %d", len(str), 32) } + str2 := GenerateRandomString() + if str2 == str { + t.Errorf("Two identical random strings in a row: %s", str) + } } func TestParseLink(t *testing.T) {