Skip to content

Commit d695bca

Browse files
committed
Use a cryptographically secure seed
`SeededSecurely` is present if someone or something wants to query the way the library was seeded. Obtained from: nomad
1 parent 0c5a487 commit d695bca

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

lib/rand.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,34 @@
11
package lib
22

33
import (
4+
crand "crypto/rand"
5+
"math"
6+
"math/big"
47
"math/rand"
58
"sync"
69
"time"
710
)
811

912
var (
1013
once sync.Once
14+
15+
// SeededSecurely is set to true if a cryptographically secure seed
16+
// was used to initialize rand. When false, the start time is used
17+
// as a seed.
18+
SeededSecurely bool
1119
)
1220

1321
// SeedMathRand provides weak, but guaranteed seeding, which is better than
1422
// running with Go's default seed of 1. A call to SeedMathRand() is expected
1523
// to be called via init(), but never a second time.
1624
func SeedMathRand() {
17-
once.Do(func() { rand.Seed(time.Now().UTC().UnixNano()) })
25+
once.Do(func() {
26+
n, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
27+
if err != nil {
28+
rand.Seed(time.Now().UTC().UnixNano())
29+
return
30+
}
31+
rand.Seed(n.Int64())
32+
SeededSecurely = true
33+
})
1834
}

0 commit comments

Comments
 (0)