From 57f6fdb0d01a005de5bbc7eace564ee946286c21 Mon Sep 17 00:00:00 2001 From: chris Date: Fri, 28 Aug 2020 11:09:08 -0400 Subject: [PATCH] Replace math/rand usage with crypto/rand This replaces the usage of math/rand with crypto/rand to support downstream usages of the random package that have security implications, such as the csrf middleware. --- random/random.go | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/random/random.go b/random/random.go index 482d052..fee2b81 100644 --- a/random/random.go +++ b/random/random.go @@ -1,9 +1,9 @@ package random import ( - "math/rand" + "bufio" + "crypto/rand" "strings" - "time" ) type ( @@ -27,7 +27,6 @@ var ( ) func New() *Random { - rand.Seed(time.Now().UnixNano()) return new(Random) } @@ -36,11 +35,16 @@ func (r *Random) String(length uint8, charsets ...string) string { if charset == "" { charset = Alphanumeric } - b := make([]byte, length) - for i := range b { - b[i] = charset[rand.Int63()%int64(len(charset))] + reader := bufio.NewReaderSize(rand.Reader, int(length)) + buf := make([]byte, length) + for i := range buf { + b, err := reader.ReadByte() + if err != nil { + panic(err) + } + buf[i] = charset[int(b)%len(charset)] } - return string(b) + return string(buf) } func String(length uint8, charsets ...string) string {