github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/helper/crypto/crypto.go (about) 1 package crypto 2 3 import ( 4 "errors" 5 "fmt" 6 7 // note: this is aliased so that it's more noticeable if someone 8 // accidentally swaps it out for math/rand via running goimports 9 cryptorand "crypto/rand" 10 ) 11 12 // Bytes gets a slice of cryptographically random bytes of the given length and 13 // enforces that we check for short reads to avoid entropy exhaustion. 14 func Bytes(length int) ([]byte, error) { 15 key := make([]byte, length) 16 n, err := cryptorand.Read(key) 17 if err != nil { 18 return nil, fmt.Errorf("could not read from random source: %v", err) 19 } 20 if n < length { 21 return nil, errors.New("entropy exhausted") 22 } 23 return key, nil 24 }