git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/crypto/rand.go (about) 1 package crypto 2 3 import ( 4 "crypto/rand" 5 "io" 6 "math/big" 7 ) 8 9 // RandBytes returns securely generated random bytes. 10 // It will return an error if the system's secure random 11 // number generator fails to function correctly, in which 12 // case the caller should not continue. 13 func RandBytes(n uint64) ([]byte, error) { 14 b := make([]byte, n) 15 16 _, err := rand.Read(b) 17 if err != nil { 18 return nil, err 19 } 20 21 return b, nil 22 } 23 24 // RandInt64Between returns a uniform random value in [min, max). 25 func RandInt64Between(min, max int64) (int64, error) { 26 n, err := rand.Int(rand.Reader, big.NewInt(max-min)) 27 if err != nil { 28 return max, err 29 } 30 return n.Int64(), nil 31 } 32 33 // RandInt64 returns a uniform random value in [0, max). 34 func RandInt64(max int64) (int64, error) { 35 n, err := rand.Int(rand.Reader, big.NewInt(max)) 36 if err != nil { 37 return max, err 38 } 39 return n.Int64(), nil 40 } 41 42 // RandAlphabet returns a buffer a size n filled with random values taken from alphabet 43 func RandAlphabet(alphabet []byte, n uint64) ([]byte, error) { 44 buffer := make([]byte, n) 45 alphabetLen := int64(len(alphabet)) 46 47 for i := range buffer { 48 n, err := RandInt64(alphabetLen) 49 if err != nil { 50 return nil, err 51 } 52 buffer[i] = alphabet[n] 53 } 54 return buffer, nil 55 } 56 57 // RandReader returns a cryptographically secure source of entropy which implements the `io.Reader` 58 // interface. 59 func RandReader() io.Reader { 60 return rand.Reader 61 }