-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerator.go
112 lines (89 loc) · 2.14 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
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"encoding/base64"
"fmt"
"math/rand"
"strings"
)
const (
LowerLetters = "abcdefghijklmnopqrstuvwxyz"
UpperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Digits = "0123456789"
Symbols = "@&$#!%*._+-=()[]{}:?<>"
)
type Generator struct {
Length int
HasSymbols bool
Encoded bool
Attempts int
AttemptsTaken int
}
func NewGenerator(length int, symbols, encoded bool) *Generator {
return &Generator{
Length: length,
HasSymbols: symbols,
Encoded: encoded,
Attempts: 10_000,
AttemptsTaken: 0,
}
}
func (g *Generator) Generate() (string, error) {
tries := g.Attempts
password := ""
for tries > 0 {
g.AttemptsTaken++
password = g.buildRandomPassword()
isValid := g.isValid(password)
if isValid {
break
}
tries--
}
if tries == 0 {
return password, fmt.Errorf("retries exausted, could not generate a password with the set requirements")
}
return password, nil
}
// A password is considered valid if its length is correct and it contains at least one of each:
// upper case letter, lower case letter, digit and symbol (if enabled).
func (g *Generator) isValid(password string) bool {
if len(password) != g.Length {
return false
}
if !strings.ContainsAny(password, Digits) {
return false
}
if g.HasSymbols {
if !strings.ContainsAny(password, Symbols) {
return false
}
}
if !strings.ContainsAny(password, LowerLetters) {
return false
}
if !strings.ContainsAny(password, UpperLetters) {
return false
}
return true
}
func (g *Generator) PrintConfig() {
fmt.Printf("Configuration:\n")
fmt.Printf("- Length: %d\n", g.Length)
fmt.Printf("- Symbols: %v\n", g.HasSymbols)
fmt.Printf("- Encoded: %v\n", g.Encoded)
fmt.Printf("- Attempts: %d\n\n", g.AttemptsTaken)
}
func (g *Generator) Base64Encode(password string) string {
return base64.StdEncoding.EncodeToString([]byte(password))
}
func (g *Generator) buildRandomPassword() string {
chars := LowerLetters + UpperLetters + Digits
if g.HasSymbols {
chars += Symbols
}
password := ""
for i := 0; i < g.Length; i++ {
password += string(chars[rand.Intn(len(chars))])
}
return password
}