-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpw.go
81 lines (63 loc) · 1.63 KB
/
pw.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
package pw
import (
"crypto/rand"
"math/big"
)
// UpperChars ...
const UpperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
// LowerChars ...
const LowerChars = "abcdefghijklmnopqrstuvwxyz"
// SpecialChars ...
const SpecialChars = "!@#$%^&*()-_=+,.?/:;{}[]~"
// NumberChars ...
const NumberChars = "0123456789"
// AllChars ...
const AllChars = UpperChars + LowerChars + SpecialChars + NumberChars
// Option type
type Option func() string
func randomFromChars(length int, chars string) string {
// rand.Int returns value in [0, max)
max := len(chars)
p := ""
for i := 0; i < length; i++ {
n, _ := rand.Int(rand.Reader, big.NewInt(int64(max)))
p = p + string(chars[n.Int64()])
}
return p
}
// WithUpperCase option to use upper case characters in the password
func WithUpperCase() Option {
return func() string {
return UpperChars
}
}
// WithLowerCase option to use lower case characters in the password
func WithLowerCase() Option {
return func() string {
return LowerChars
}
}
// WithNumbers option to use number characters in the password
func WithNumbers() Option {
return func() string {
return NumberChars
}
}
// WithSpecial option to use special characters in the password
func WithSpecial() Option {
return func() string {
return SpecialChars
}
}
// NewPassword to create a new password with length. Defaults characters to include
// all characters. Options can be passed to customize the password.
func NewPassword(length int, options ...Option) string {
if len(options) != 0 {
c := ""
for _, option := range options {
c = c + option()
}
return randomFromChars(length, c)
}
return randomFromChars(length, AllChars)
}