-
Notifications
You must be signed in to change notification settings - Fork 0
/
csprng.go
42 lines (36 loc) · 829 Bytes
/
csprng.go
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
package generic
import (
"crypto/rand"
"encoding/hex"
"io"
"os"
)
// CSPRNG is a cryptographically secure pseudo-random number generator for byte slices
func CSPRNG(n int64) ([]byte, error) {
random := make([]byte, n)
if _, err := io.ReadFull(rand.Reader, random); err != nil {
return []byte{}, err
}
return random, nil
}
// CSPRNGHex is a CSPRNG in hex format
func CSPRNGHex(n int64) (string, error) {
rnd, err := CSPRNG(n)
return hex.EncodeToString(rnd), err
}
// HWRng is a hardware random number generator
func HWRng(n int64) ([]byte, error) {
file, err := os.Open("/dev/hwrng")
if err != nil {
return nil, err
}
defer file.Close()
random := make([]byte, n)
if _, err = io.ReadFull(file, random); err != nil {
return nil, err
}
return random, nil
}
func Rand() io.Reader {
return rand.Reader
}