Skip to content

Commit

Permalink
sioutil: add Random and MustRandom helper functions
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Andreas Auernhammer committed Oct 29, 2019
1 parent 87b0a09 commit a453e49
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions sioutil/sio.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package sioutil

import (
"crypto/rand"
"io"

"golang.org/x/sys/cpu"
Expand Down Expand Up @@ -49,3 +50,30 @@ func NativeAES() bool {
return cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR &&
(cpu.S390X.HasAESGCM || cpu.S390X.HasGHASH)
}

// Random returns n randomly generated bytes if
// and only if err == nil.
//
// Random uses crypto/rand.Reader as cryptographically
// secure random number generator (CSPRNG).
func Random(n int) (b []byte, err error) {
b = make([]byte, n)
if _, err = io.ReadFull(rand.Reader, b); err != nil {
return nil, err
}
return b, nil
}

// MustRandom returns n randomly generated bytes.
// It panics if it fails to read n random bytes
// from its entropy source.
//
// MustRandom uses crypto/rand.Reader as cryptographically
// secure random number generator (CSPRNG).
func MustRandom(n int) []byte {
b, err := Random(n)
if err != nil {
panic("sioutil: out of entropy: " + err.Error())
}
return b
}

0 comments on commit a453e49

Please sign in to comment.