-
Notifications
You must be signed in to change notification settings - Fork 1
/
genhash.go
73 lines (59 loc) · 1.64 KB
/
genhash.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
package cmd
import (
"errors"
"fmt"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"golang.org/x/crypto/bcrypt"
)
type promptContent struct {
errorMsg string
label string
}
func promptGetInput(pc promptContent) string {
validate := func(input string) error {
if len(input) <= 0 {
return errors.New(pc.errorMsg)
}
return nil
}
prompt := promptui.Prompt{
Label: pc.label,
Validate: validate,
}
result, err := prompt.Run()
if err != nil {
logger.WithError(err).Fatal("Prompt failed")
}
return result
}
// generateHashCmd represents the generateHash command
var genpwdhash = &cobra.Command{
Use: "genpwdhash",
Short: "Generate bcrypt hash from provided password for RPC authentication",
Long: "The generated output is to be used as server password hash (server.pwdhash)",
Run: func(cmd *cobra.Command, args []string) {
cost, err := cmd.Flags().GetInt("cost")
if err != nil {
logger.WithError(err).Fatal("could not get cost value")
}
if cost < bcrypt.MinCost || cost > bcrypt.MaxCost {
logger.Fatalf("cost outside of range [%d,%d]", bcrypt.MinCost, bcrypt.MaxCost)
}
passwordInputPrompt := promptContent{
"Please provide your password.",
"Password",
}
passwordInput := promptGetInput(passwordInputPrompt)
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(passwordInput), cost)
if err != nil {
logger.WithError(err).Fatal("could not generate bcrypt hash")
}
fmt.Printf("%q\n", string(hashedPassword))
},
}
func init() {
rootCmd.AddCommand(genpwdhash)
generateHashFlags := genpwdhash.Flags()
generateHashFlags.Int("cost", 10, "Default cost for bcrypt hashing")
}