|
5 | 5 | package rand |
6 | 6 |
|
7 | 7 | import ( |
8 | | - "math/rand/v2" |
| 8 | + crand "crypto/rand" |
| 9 | + "io" |
| 10 | + mrand "math/rand/v2" |
9 | 11 | "unsafe" |
10 | 12 | ) |
11 | 13 |
|
12 | 14 | var words = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") |
13 | 15 |
|
14 | | -func appendBytes(data []byte, n int) []byte { |
15 | | - length := len(words) |
16 | | - for i := 0; i < n; i++ { |
17 | | - index := rand.IntN(length) |
18 | | - data = append(data, words[index]) |
| 16 | +func readFull(data []byte, n int) []byte { |
| 17 | + for i := 0; i < n && i < len(data); i++ { |
| 18 | + index := mrand.IntN(len(words)) |
| 19 | + data[i] = words[index] |
19 | 20 | } |
20 | 21 |
|
21 | 22 | return data |
22 | 23 | } |
23 | 24 |
|
24 | 25 | // Bytes returns n bytes in random which can be used to generate an iv. |
25 | | -func Bytes(n int) []byte { |
26 | | - data := make([]byte, 0, n) |
27 | | - data = appendBytes(data, n) |
| 26 | +func Bytes(n int, opts ...Option) []byte { |
| 27 | + conf := newConfig().Apply(opts...) |
| 28 | + |
| 29 | + data := make([]byte, n) |
| 30 | + if conf.weak { |
| 31 | + readFull(data, n) |
| 32 | + } else { |
| 33 | + io.ReadFull(crand.Reader, data) |
| 34 | + } |
| 35 | + |
28 | 36 | return data |
29 | 37 | } |
30 | 38 |
|
31 | 39 | // String returns a string including n bytes in random which can be used to generate an iv. |
32 | | -func String(n int) string { |
33 | | - data := Bytes(n) |
| 40 | +func String(n int, opts ...Option) string { |
| 41 | + data := Bytes(n, opts...) |
34 | 42 | ptr := unsafe.SliceData(data) |
35 | 43 | return unsafe.String(ptr, len(data)) |
36 | 44 | } |
0 commit comments