-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathpasswordgenerator.go
More file actions
39 lines (34 loc) · 1002 Bytes
/
passwordgenerator.go
File metadata and controls
39 lines (34 loc) · 1002 Bytes
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
// 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_generator
import (
crand "crypto/rand"
"io"
"math/rand"
)
// GeneratePassword returns a newly generated password
func GeneratePassword(minLength int, maxLength int) string {
var chars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,.?/:;{}[]`~")
var length = rand.Intn(maxLength-minLength) + minLength
newPassword := make([]byte, length)
randomData := make([]byte, length+(length/4))
clen := byte(len(chars))
maxrb := byte(256 - (256 % len(chars)))
i := 0
for {
if _, err := io.ReadFull(crand.Reader, randomData); err != nil {
panic(err)
}
for _, c := range randomData {
if c >= maxrb {
continue
}
newPassword[i] = chars[c%clen]
i++
if i == length {
return string(newPassword)
}
}
}
}