Skip to content

Commit a453e49

Browse files
author
Andreas Auernhammer
committed
sioutil: add Random and MustRandom helper functions
This commit adds two helper functions for generating random bytes. As a user of `sio` you may need to generate a random nonce: ``` import "crypto/rand" nonce := make([]byte, stream.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { // TODO: error handling } ``` Such code is quite tedious to write / verbose and has two style issues: - It requires some care to ALWAYS use "crypto/rand" as source of entropy. Especially, with editor / IDE tooling like goimports it is easy to import an insecure (b/c no CSPRNG) entropy source. - Often applications cannot / do not implement reasonable error handling. Usually, an application cannot recover into a reasonable state when it cannot read from the entropy source of the system. This situation is kind of similar to running out-of-memory. With the new helper functions a library (which may prefer to not panic) can do just: ``` nonce, err := sioutil.Random(stream.NonceSize()) if err != nil { // TODO: error handling - usually return to caller. } ``` An application may want to call: `nonce := sioutil.MustRandom(stream.NonceSize())` instead.
1 parent 87b0a09 commit a453e49

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

sioutil/sio.go

+28
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
package sioutil
77

88
import (
9+
"crypto/rand"
910
"io"
1011

1112
"golang.org/x/sys/cpu"
@@ -49,3 +50,30 @@ func NativeAES() bool {
4950
return cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR &&
5051
(cpu.S390X.HasAESGCM || cpu.S390X.HasGHASH)
5152
}
53+
54+
// Random returns n randomly generated bytes if
55+
// and only if err == nil.
56+
//
57+
// Random uses crypto/rand.Reader as cryptographically
58+
// secure random number generator (CSPRNG).
59+
func Random(n int) (b []byte, err error) {
60+
b = make([]byte, n)
61+
if _, err = io.ReadFull(rand.Reader, b); err != nil {
62+
return nil, err
63+
}
64+
return b, nil
65+
}
66+
67+
// MustRandom returns n randomly generated bytes.
68+
// It panics if it fails to read n random bytes
69+
// from its entropy source.
70+
//
71+
// MustRandom uses crypto/rand.Reader as cryptographically
72+
// secure random number generator (CSPRNG).
73+
func MustRandom(n int) []byte {
74+
b, err := Random(n)
75+
if err != nil {
76+
panic("sioutil: out of entropy: " + err.Error())
77+
}
78+
return b
79+
}

0 commit comments

Comments
 (0)