-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
95 lines (81 loc) · 2.27 KB
/
main.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
package main
import (
"crypto/rand"
"fmt"
"math/big"
"os"
"strings"
"github.com/spf13/cobra"
)
var (
letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
lettersAndSpecial = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+{}|:<>?`~-=[]\\;',./")
lettersFlag bool
specialFlag bool
lengthFlag int
excludeFlag string
)
func main() {
var rootCmd = &cobra.Command{
Use: "pwdgen",
Short: "A CLI tool to generate passwords with entropy and complexity",
Long: `A CLI tool to generate passwords with entropy and complexity`,
Run: func(cmd *cobra.Command, args []string) {
if lettersFlag && specialFlag {
fmt.Println("Error: -l (letters) and -s (special) flags cannot be used together.")
os.Exit(1)
}
password := generatePassword(lengthFlag)
if excludeFlag != "" {
fmt.Println(excludeCharacters(password))
} else {
fmt.Println(password)
}
},
}
rootCmd.Flags().BoolVarP(&lettersFlag, "letters", "l", false, "use letters and numbers")
rootCmd.Flags().BoolVarP(&specialFlag, "special", "s", false, "use letters, numbers and special characters")
rootCmd.Flags().IntVarP(&lengthFlag, "length", "n", 20, "length of the password")
rootCmd.Flags().StringVarP(&excludeFlag, "exclude", "e", "", "exclude characters from the password")
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func generatePassword(length int) string {
var characters []rune
if specialFlag {
characters = lettersAndSpecial
} else {
characters = letters
}
var password strings.Builder
password.Grow(length)
for i := 0; i < length; i++ {
char, err := rand.Int(rand.Reader, big.NewInt(int64(len(characters))))
if err != nil {
fmt.Println("Error generating random character:", err)
continue
}
password.WriteRune(characters[char.Int64()])
}
return password.String()
}
func excludeCharacters(password string) string {
var newPassword strings.Builder
newPassword.Grow(len(password))
for _, char := range password {
if !containsRune(excludeFlag, char) {
newPassword.WriteRune(char)
}
}
return newPassword.String()
}
func containsRune(s string, r rune) bool {
for _, a := range s {
if a == r {
return true
}
}
return false
}