-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
random.go
78 lines (73 loc) · 2.02 KB
/
random.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Package random holds a few functions for working with random numbers
package random
import (
cryptorand "crypto/rand"
"encoding/base64"
"encoding/binary"
"fmt"
mathrand "math/rand"
)
// StringFn create a random string for test purposes using the random
// number generator function passed in.
//
// Do not use these for passwords.
func StringFn(n int, randIntn func(n int) int) string {
const (
vowel = "aeiou"
consonant = "bcdfghjklmnpqrstvwxyz"
digit = "0123456789"
)
pattern := []string{consonant, vowel, consonant, vowel, consonant, vowel, consonant, digit}
out := make([]byte, n)
p := 0
for i := range out {
source := pattern[p]
p = (p + 1) % len(pattern)
out[i] = source[randIntn(len(source))]
}
return string(out)
}
// String create a random string for test purposes.
//
// Do not use these for passwords.
func String(n int) string {
return StringFn(n, mathrand.Intn)
}
// Password creates a crypto strong password which is just about
// memorable. The password is composed of printable ASCII characters
// from the base64 alphabet.
//
// Requires password strength in bits.
// 64 is just about memorable
// 128 is secure
func Password(bits int) (password string, err error) {
bytes := bits / 8
if bits%8 != 0 {
bytes++
}
var pw = make([]byte, bytes)
n, err := cryptorand.Read(pw)
if err != nil {
return "", fmt.Errorf("password read failed: %w", err)
}
if n != bytes {
return "", fmt.Errorf("password short read: %d", n)
}
password = base64.RawURLEncoding.EncodeToString(pw)
return password, nil
}
// Seed the global math/rand with crypto strong data
//
// This doesn't make it OK to use math/rand in crypto sensitive
// environments - don't do that! However it does help to mitigate the
// problem if that happens accidentally. This would have helped with
// CVE-2020-28924 - #4783
func Seed() error {
var seed int64
err := binary.Read(cryptorand.Reader, binary.LittleEndian, &seed)
if err != nil {
return fmt.Errorf("failed to read random seed: %w", err)
}
mathrand.Seed(seed)
return nil
}