-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpassword.go
90 lines (83 loc) · 1.75 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
83
84
85
86
87
88
89
90
package password
import (
"crypto/rand"
"errors"
"fmt"
"math/big"
)
const (
digits = "0123456789"
symbols = ".:;,/?!_-<>()[]*%=$&@#"
lettersLower = "abcdefghijklmnopqrstuvwxyz"
lettersUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
// Config contains the parameters to generate a passwords' list
type Config struct {
// Number of passwords to generate
Number int
// Length of the generated passwords
Length int
// Digits required
Digits bool
// Symbols required
Symbols bool
// Lower case characters required
Lower bool
// Upper case characters required
Upper bool
}
// DefaultConfig stores default parameters for the generator
var DefaultConfig = Config{
Number: 10,
Length: 21,
Digits: true,
Symbols: true,
Lower: true,
Upper: true,
}
// New returns a Config to pass to the generator
func New() *Config {
return &DefaultConfig
}
// Generate returns a list of passwords based on the provided Config
func Generate(c *Config) []string {
if c == nil {
c = New()
}
chars, err := getCharacters(c)
if err != nil {
fmt.Println(err)
return []string{}
}
list := make([]string, c.Number)
rd := rand.Reader
for i := 0; i < c.Number; i++ {
var pwd string
for j := 0; j < c.Length; j++ {
n, _ := rand.Int(rd, big.NewInt(int64(len(chars))))
pwd = pwd + string(chars[n.Int64()])
}
list[i] = pwd
}
return list
}
// getCharacters returns the string with authorized characters for the password
func getCharacters(c *Config) (string, error) {
var chars string
if c.Digits {
chars += digits
}
if c.Symbols {
chars += symbols
}
if c.Lower {
chars += lettersLower
}
if c.Upper {
chars += lettersUpper
}
if len(chars) == 0 {
return chars, errors.New("cannot generate password from empty set")
}
return chars, nil
}