Bläddra i källkod

Merge pull request #15123 from ewindisch/seed-pkgrand-cryptorand

Prefer crypto rand seed for pkg/rand
Tibor Vass 10 år sedan
förälder
incheckning
9a9a12b351
1 ändrade filer med 11 tillägg och 1 borttagningar
  1. 11 1
      pkg/random/random.go

+ 11 - 1
pkg/random/random.go

@@ -1,7 +1,10 @@
 package random
 package random
 
 
 import (
 import (
+	cryptorand "crypto/rand"
 	"io"
 	"io"
+	"math"
+	"math/big"
 	"math/rand"
 	"math/rand"
 	"sync"
 	"sync"
 	"time"
 	"time"
@@ -36,8 +39,15 @@ func (r *lockedSource) Seed(seed int64) {
 // NewSource returns math/rand.Source safe for concurrent use and initialized
 // NewSource returns math/rand.Source safe for concurrent use and initialized
 // with current unix-nano timestamp
 // with current unix-nano timestamp
 func NewSource() rand.Source {
 func NewSource() rand.Source {
+	var seed int64
+	if cryptoseed, err := cryptorand.Int(cryptorand.Reader, big.NewInt(math.MaxInt64)); err != nil {
+		// This should not happen, but worst-case fallback to time-based seed.
+		seed = time.Now().UnixNano()
+	} else {
+		seed = cryptoseed.Int64()
+	}
 	return &lockedSource{
 	return &lockedSource{
-		src: rand.NewSource(time.Now().UnixNano()),
+		src: rand.NewSource(seed),
 	}
 	}
 }
 }