forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
46 lines (40 loc) · 1.19 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
// 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
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)
clen := 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%clen]
i++
if i == intLength {
return string(newPassword)
}
}
}
}