Skip to content

Commit 6be1399

Browse files
authored
Merge pull request #36 from smallstep/herman/bytes
Add Bytes() function
2 parents 2179282 + d67e21a commit 6be1399

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

randutil/random.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,16 @@ func Salt(size int) ([]byte, error) {
3131
return salt, nil
3232
}
3333

34+
// Bytes generates a new byte slice of the given size.
35+
func Bytes(size int) ([]byte, error) {
36+
bytes := make([]byte, size)
37+
_, err := io.ReadFull(rand.Reader, bytes)
38+
if err != nil {
39+
return nil, errors.Wrap(err, "error generating bytes")
40+
}
41+
return bytes, nil
42+
}
43+
3444
// String returns a random string of a given length using the characters in
3545
// the given string. It splits the string on runes to support UTF-8
3646
// characters.

randutil/random_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,18 @@ func TestSalt(t *testing.T) {
5959
}
6060
}
6161

62+
func TestBytes(t *testing.T) {
63+
sizes := []int{4, 8, 16, 32, 64, 128}
64+
for _, size := range sizes {
65+
a, err := Bytes(size)
66+
assert.NoError(t, err)
67+
b, err := Bytes(size)
68+
assert.NoError(t, err)
69+
// Most of the time
70+
assert.NotEquals(t, a, b)
71+
}
72+
}
73+
6274
func TestString(t *testing.T) {
6375
re := regexp.MustCompilePOSIX(`^[0-9世界ñçàèìòù]+$`)
6476
chars := "0123456789世界ñçàèìòù"

0 commit comments

Comments
 (0)