-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrandom.go
More file actions
55 lines (46 loc) · 1.3 KB
/
random.go
File metadata and controls
55 lines (46 loc) · 1.3 KB
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
48
49
50
51
52
53
54
55
package suk
import (
"crypto/rand"
"fmt"
"io"
"math/big"
)
const (
// defaultPossibleKeyCharacters contains all characters used to randomly
// generate keys.
defaultPossibleKeyCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.-_"
)
// Most of this code was taken from
// https://gist.github.com/dopey/c69559607800d2f2f90b1b1ed4e550fb
func init() {
assertAvailablePRNG()
}
// assertAvailablePRNG asserts that there is an available pseudorandom number
// generator, which is used to create random IDs via randomID.
func assertAvailablePRNG() {
buf := make([]byte, 1)
_, err := io.ReadFull(rand.Reader, buf)
if err != nil {
panic(
fmt.Sprintf("crypto/rand is unavailable: Read() failed with %#v", err),
)
}
}
// defaultRandomKeyGenerator returns a securely generated random string. It will
// return an error if the system's secure random number generator fails to
// function correctly, in which case the caller should not continue.
func defaultRandomKeyGenerator(n uint64) (string, error) {
ret := make([]byte, n)
var i uint64
for i = 0; i < n; i++ {
num, err := rand.Int(
rand.Reader,
big.NewInt(int64(len(defaultPossibleKeyCharacters))),
)
if err != nil {
return "", err
}
ret[i] = defaultPossibleKeyCharacters[num.Int64()]
}
return string(ret), nil
}