Prefer crypto rand seed for pkg/rand

Crypto rand is a much better seed for math/rand than
time. In the event we use math/rand where we should not,
this will make it a safer source of random numbers.

Although potentially dangerous, this will still fallback
to time should crypto/rand for any reason fail.

Signed-off-by: Eric Windisch <eric@windisch.us>
Upstream-commit: 4742a3964fd276a825a5ff4d1cf8417ae88abcb1
Component: engine
This commit is contained in:
Eric Windisch
2015-07-29 12:55:57 -04:00
parent 9d7f169c3f
commit f7e9c2e779
+11 -1
View File
@@ -1,7 +1,10 @@
package random
import (
cryptorand "crypto/rand"
"io"
"math"
"math/big"
"math/rand"
"sync"
"time"
@@ -36,8 +39,15 @@ func (r *lockedSource) Seed(seed int64) {
// NewSource returns math/rand.Source safe for concurrent use and initialized
// with current unix-nano timestamp
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{
src: rand.NewSource(time.Now().UnixNano()),
src: rand.NewSource(seed),
}
}