-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
generator.go
49 lines (42 loc) · 1.24 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
// This program generates a password from a list of possible chars
// You must provide a minimum length and a maximum length
// This length is not fixed if you generate multiple passwords for the same range
// Package password contains functions to help generate random passwords
// time complexity: O(n)
// space complexity: O(n)
package password
import (
"crypto/rand"
"io"
"math/big"
)
// Generate returns a newly generated password
func Generate(minLength int, maxLength int) string {
var chars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,.?/:;{}[]`~")
length, err := rand.Int(rand.Reader, big.NewInt(int64(maxLength-minLength)))
if err != nil {
panic(err) // handle this gracefully
}
length.Add(length, big.NewInt(int64(minLength)))
intLength := int(length.Int64())
newPassword := make([]byte, intLength)
randomData := make([]byte, intLength+intLength/4)
charLen := byte(len(chars))
maxrb := byte(256 - (256 % len(chars)))
i := 0
for {
if _, err := io.ReadFull(rand.Reader, randomData); err != nil {
panic(err)
}
for _, c := range randomData {
if c >= maxrb {
continue
}
newPassword[i] = chars[c%charLen]
i++
if i == intLength {
return string(newPassword)
}
}
}
}