-
Notifications
You must be signed in to change notification settings - Fork 4
/
generate.go
96 lines (74 loc) · 1.71 KB
/
generate.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
package main
import (
"crypto/rand"
"fmt"
"math/big"
"strconv"
"github.com/atotto/clipboard"
"github.com/spf13/cobra"
)
const (
lowerCaseBytes = "abcdefghijklmnopqrstuvwxyz"
upperCaseBytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digitBytes = "0123456789"
specialBytes = " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
)
func generateCmd(_ *cobra.Command, _ []string) error {
var passwordBytes string
passwordLengthStr, err := readString("Desired password length? ")
if err != nil {
return err
}
passwordLength, err := strconv.Atoi(passwordLengthStr)
if err != nil {
return err
}
addLowerCase, err := readString("Lower case letters? [y/n] ")
if err != nil {
return err
}
if addLowerCase == `y` {
passwordBytes += lowerCaseBytes
}
addUpperCase, err := readString("Upper case letter? [y/n] ")
if err != nil {
return err
}
if addUpperCase == `y` {
passwordBytes += upperCaseBytes
}
addDigits, err := readString("Digits? [y/n] ")
if err != nil {
return err
}
if addDigits == `y` {
passwordBytes += digitBytes
}
addSpecial, err := readString("Special characters? [y/n] ")
if err != nil {
return err
}
if addSpecial == `y` {
passwordBytes += specialBytes
}
password, err := generatePassword(passwordBytes, passwordLength)
if err != nil {
return err
}
if err := clipboard.WriteAll(password); err != nil {
return err
}
fmt.Println("Copied password to clipboard")
return nil
}
func generatePassword(baseBytes string, length int) (string, error) {
var password string
for i := 0; i < length; i++ {
val, err := rand.Int(rand.Reader, big.NewInt(int64(len(baseBytes))))
if err != nil {
return "", err
}
password += string(baseBytes[val.Int64()])
}
return password, nil
}