-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmd.go
More file actions
86 lines (70 loc) · 1.95 KB
/
cmd.go
File metadata and controls
86 lines (70 loc) · 1.95 KB
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
package main
import (
"crypto/rand"
"fmt"
"math/big"
"github.com/spf13/cobra"
)
const VERSION string = "1.1.0"
type CmdOptions struct {
Length int64
Count int64
Additional string
AlphabetFlag bool
NumberFlag bool
SpecialFlag bool
ShowVersion bool
}
func RandomFromText(text string, length int64) (string, error) {
if len(text) == 0 || length <= 0 {
return "", nil
}
result := make([]rune, length)
runes := []rune(text)
for i := range length {
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(runes))))
if err != nil {
return "", err
}
result[i] = runes[n.Int64()]
}
return string(result), nil
}
func NewRootCommand() *cobra.Command {
var opts CmdOptions
cmd := &cobra.Command{
Use: "entropykey",
Short: "Tiny utility to generate random secure passwords",
Run: func(cmd *cobra.Command, args []string) {
if opts.ShowVersion {
fmt.Println("EntropyKey v" + VERSION)
return
}
chars := opts.Additional
if opts.AlphabetFlag {
chars += "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
}
if opts.NumberFlag {
chars += "1234567890"
}
if opts.SpecialFlag {
chars += "!#$%&()*+,-./:;<=>?@[]^_{|}~"
}
for range opts.Count {
if password, err := RandomFromText(chars, opts.Length); err == nil {
fmt.Println(password)
} else {
panic(err)
}
}
},
}
cmd.Flags().Int64VarP(&opts.Length, "length", "l", 16, "Passphrase length")
cmd.Flags().Int64VarP(&opts.Count, "count", "c", 4, "Passphrase count")
cmd.Flags().StringVarP(&opts.Additional, "chars", "C", "", "Additional characters")
cmd.Flags().BoolVarP(&opts.AlphabetFlag, "alphabet", "a", true, "Add alphabet characters")
cmd.Flags().BoolVarP(&opts.NumberFlag, "number", "n", true, "Add number characters")
cmd.Flags().BoolVarP(&opts.SpecialFlag, "special", "s", false, "Add special characters")
cmd.Flags().BoolVarP(&opts.ShowVersion, "version", "v", false, "Show version")
return cmd
}