replace math/rand with crypto/rand

This commit is contained in:
Tan Jiang 2017-04-25 15:35:08 +08:00
parent f1d8310ed8
commit da19700a1e
2 changed files with 11 additions and 3 deletions

View File

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

View File

@ -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) {