diff --git a/randutil/random.go b/randutil/random.go index 642e661a..dce7931b 100644 --- a/randutil/random.go +++ b/randutil/random.go @@ -31,6 +31,16 @@ func Salt(size int) ([]byte, error) { return salt, nil } +// Bytes generates a new byte slice of the given size. +func Bytes(size int) ([]byte, error) { + bytes := make([]byte, size) + _, err := io.ReadFull(rand.Reader, bytes) + if err != nil { + return nil, errors.Wrap(err, "error generating bytes") + } + return bytes, nil +} + // String returns a random string of a given length using the characters in // the given string. It splits the string on runes to support UTF-8 // characters. diff --git a/randutil/random_test.go b/randutil/random_test.go index afdc4706..d42aea4e 100644 --- a/randutil/random_test.go +++ b/randutil/random_test.go @@ -59,6 +59,18 @@ func TestSalt(t *testing.T) { } } +func TestBytes(t *testing.T) { + sizes := []int{4, 8, 16, 32, 64, 128} + for _, size := range sizes { + a, err := Bytes(size) + assert.NoError(t, err) + b, err := Bytes(size) + assert.NoError(t, err) + // Most of the time + assert.NotEquals(t, a, b) + } +} + func TestString(t *testing.T) { re := regexp.MustCompilePOSIX(`^[0-9世界ñçàèìòù]+$`) chars := "0123456789世界ñçàèìòù"