-
Notifications
You must be signed in to change notification settings - Fork 8
/
password.go
82 lines (72 loc) · 1.42 KB
/
password.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
package main
import (
"crypto/rand"
"errors"
)
const (
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lower = "abcdefghijklmnopqrstuvwxyz"
number = "0123456789"
special = "@%-_+,./:"
chars = upper + lower + number + special
)
type PasswordGenerator func(int) string
type password struct {
Password string
Upper int
Lower int
Number int
Special int
}
func GenerateSecurePassword(n int) string {
for {
p, err := generatePassword(n)
if err != nil {
continue
}
err = ValidatePassword(p)
if err == nil {
return p.Password
}
}
}
func ValidatePassword(p password) error {
if p.Password[0] != '-' &&
(p.Upper > 0 || p.Lower > 0 || p.Number > 0 || p.Special > 0) {
return nil
}
return errors.New("Invalid password")
}
func (p *password) AddChar(idx int) {
p.Password = p.Password + string(chars[idx])
switch {
case idx < len(upper):
p.Upper = p.Upper + 1
case idx < len(upper)+len(lower):
p.Lower = p.Lower + 1
case idx < len(upper)+len(lower)+len(special):
p.Number = p.Number + 1
default:
p.Special = p.Special + 1
}
}
func generatePassword(n int) (password, error) {
b, err := randomBytes(n)
if err != nil {
return password{}, err
}
p := password{}
for _, char := range b {
idx := int(char) % len(chars)
p.AddChar(idx)
}
return p, nil
}
func randomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
return nil, err
}
return b, nil
}