-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
99 lines (82 loc) · 1.87 KB
/
generator.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package genpass
import (
"crypto/rand"
"io"
)
const (
lowerLetters = "abcdefghijklmnopqrstuvwxyz"
upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
symbols = "~!@#$%^&*()_-+?"
)
type characterType int
type typeCase int
type generator struct {
CharacterType characterType
TypeCase typeCase // only used when alpha characters are involved
Length int
randomnessGenerator io.Reader
}
func newGenerator(opts ...Param) *generator {
g := &generator{
Length: 8,
CharacterType: Numeric,
TypeCase: Lowercase,
randomnessGenerator: rand.Reader,
}
for _, f := range opts {
f(g)
}
return g
}
func (p generator) Generate() string {
pwdLength := p.Length
randValues := make([]byte, pwdLength)
_, err := p.randomnessGenerator.Read(randValues)
if err != nil {
return ""
}
pwd := make([]rune, len(randValues))
for i, randVal := range randValues {
pwd[i] = p.getCharacter(randVal)
}
return string(pwd)
}
func (p generator) getCharacter(b byte) rune {
i := int(b)
switch p.CharacterType {
case AlphanumericWithSymbols:
return p.alphanumWithSymbols(i)
case Alphabetic:
return p.alpha(i)
case Alphanumeric:
return p.alphanum(i)
default:
return p.digit(i)
}
}
func (p generator) digit(i int) rune {
return p.getRuneFrom(digits, i)
}
func (p generator) alpha(i int) rune {
return p.getRuneFrom(p.casedLetters(), i)
}
func (p generator) alphanum(i int) rune {
return p.getRuneFrom(p.casedLetters()+digits, i)
}
func (p generator) alphanumWithSymbols(i int) rune {
return p.getRuneFrom(p.casedLetters()+digits+symbols, i)
}
func (p generator) casedLetters() string {
switch p.TypeCase {
case Uppercase:
return upperLetters
case Lowercase:
return lowerLetters
default:
return upperLetters + lowerLetters
}
}
func (p generator) getRuneFrom(str string, i int) rune {
return rune(str[i%len(str)])
}