-
Notifications
You must be signed in to change notification settings - Fork 6
/
rand.go
73 lines (65 loc) · 2.32 KB
/
rand.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
package strings
import (
crand "crypto/rand"
"math/big"
"math/rand"
)
const AlphaLower = "abcdefghijklmnopqrstuvwxyz"
const AlphaUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const AlphaNum = "0123456789"
const AlphaAll = AlphaLower + AlphaUpper + AlphaNum
const Token68 = AlphaAll + "-._~+/"
// RandomString generates a pseudo random string of the given length using the given characters.
// The distribution is not perfect, but works for general purposes
func RandomString(source string, n int) string {
b := make([]byte, n)
for i := range b {
b[i] = source[rand.Int()%len(source)]
}
return string(b)
}
const passwordLower = "abcdefghijkmnopqrstuvwxyz"
const passwordUpper = "ABCDEFGHJKLMNPQRSTUVWXYZ"
const passwordNum = "23456789"
const passwordSym = "!@#%?+=_"
const passwordBytes = passwordLower + passwordUpper + passwordNum + passwordSym
// PasswordString generates a pseudo random password with the given length using characters that are common in passwords.
// We attempt to leave out letters that are easily visually confused.
// Specific letters excluded are lowercase l, upper case I and the number 1, upper case O and the number 0
// Also, only easily identifiable and describable symbols are used.
// It also tries to protect against accidentally creating an easily guessed value by making sure the password has at
// least one lower-case letter, one upper-case letter, one number, and one symbol.
// n must be at least 4
func PasswordString(n int) string {
if n < 4 {
panic("n must be at least 4")
}
b := make([]byte, n)
b[0] = passwordLower[rand.Int()%len(passwordLower)]
b[1] = passwordUpper[rand.Int()%len(passwordUpper)]
b[2] = passwordNum[rand.Int()%len(passwordNum)]
b[3] = passwordSym[rand.Int()%len(passwordSym)]
for i := 4; i < len(b); i++ {
b[i] = passwordBytes[rand.Int()%len(passwordBytes)]
}
rand.Shuffle(n, func(i, j int) {
temp := b[i]
b[i] = b[j]
b[j] = temp
})
return string(b)
}
// CryptoString returns a cryptographically secure random string from the given source.
// Use AlphaAll, AlphaUpper, AlphaLower, or AlphaNum as shortcuts for source.
func CryptoString(source string, n int) string {
ret := make([]byte, n)
l := big.NewInt(int64(len(source)))
for i := 0; i < n; i++ {
num, err := crand.Int(crand.Reader, l)
if err != nil {
return ""
}
ret[i] = source[num.Int64()]
}
return string(ret)
}