summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/sean-/seed/init.go
blob: 248d6b636c71e5127df524bd81771f129aa22fe5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package seed

import (
	crand "crypto/rand"
	"fmt"
	"math"
	"math/big"
	"math/rand"
	"sync"
	"sync/atomic"
	"time"
)

var (
	m      sync.Mutex
	secure int32
	seeded int32
)

func cryptoSeed() error {
	defer atomic.StoreInt32(&seeded, 1)

	var err error
	var n *big.Int
	n, err = crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
	if err != nil {
		rand.Seed(time.Now().UTC().UnixNano())
		return err
	}
	rand.Seed(n.Int64())
	atomic.StoreInt32(&secure, 1)
	return nil
}

// Init provides best-effort seeding (which is better than running with Go's
// default seed of 1).  If `/dev/urandom` is available, Init() will seed Go's
// runtime with entropy from `/dev/urandom` and return true because the runtime
// was securely seeded.  If Init() has already initialized the random number or
// it had failed to securely initialize the random number generation, Init()
// will return false.  See MustInit().
func Init() (seededSecurely bool, err error) {
	if atomic.LoadInt32(&seeded) == 1 {
		return false, nil
	}

	// Slow-path
	m.Lock()
	defer m.Unlock()

	if err := cryptoSeed(); err != nil {
		return false, err
	}

	return true, nil
}

// MustInit provides guaranteed secure seeding.  If `/dev/urandom` is not
// available, MustInit will panic() with an error indicating why reading from
// `/dev/urandom` failed.  MustInit() will upgrade the seed if for some reason a
// call to Init() failed in the past.
func MustInit() {
	if atomic.LoadInt32(&secure) == 1 {
		return
	}

	// Slow-path
	m.Lock()
	defer m.Unlock()

	if err := cryptoSeed(); err != nil {
		panic(fmt.Sprintf("Unable to seed the random number generator: %v", err))
	}
}

// Secure returns true if a cryptographically secure seed was used to
// initialize rand.
func Secure() bool {
	return atomic.LoadInt32(&secure) == 1
}

// Seeded returns true if Init has seeded the random number generator.
func Seeded() bool {
	return atomic.LoadInt32(&seeded) == 1
}