blob: be95366001fe64f2df2be2d4680bfb9a0c08fcaf (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
// Copyright © 2020 rsiddharth <s@ricketyspace.net>
// SPDX-License-Identifier: ISC
package lib
import (
"crypto/rand"
"math/big"
)
// Return a random number from range [min, max]
func RandomInt(min, max int64) int64 {
if min >= max {
panic("RandomInt: min cannot be >= max!")
}
var rn *big.Int
var err error
for {
rn, err = rand.Int(rand.Reader, big.NewInt(max+1))
if err != nil {
panic(err)
}
if rn.Int64() >= min {
return rn.Int64()
}
}
}
func RandomBytes(size int) ([]byte, error) {
k := make([]byte, size)
_, err := rand.Read(k)
if err != nil {
return []byte{}, err
}
return k, nil
}
// Randomly generates `min` to `max` bytes.
func RandomBytesWithLengthBetween(min, max int64) []byte {
bs := make([]byte, RandomInt(min, max))
_, err := rand.Read(bs)
if err != nil {
panic(err)
}
return bs
}
|