impexp.go 2.38 KB
Newer Older
ElyKar's avatar
ElyKar committed
1 2 3 4 5 6 7 8
package cmd

import (
	"fmt"
	"os"

	"dfss/dfssc/common"
	"dfss/dfssc/user"
9
	"github.com/spf13/cobra"
ElyKar's avatar
ElyKar committed
10 11 12 13 14 15 16
)

// export the certificate and private key of the user
var exportCmd = &cobra.Command{
	Use:   "export <c>",
	Short: "export certificate and private key of the user to file c",
	Run: func(cmd *cobra.Command, args []string) {
17 18 19 20 21 22
		if len(args) != 1 {
			_ = cmd.Usage()
			os.Exit(1)
			return
		}

ElyKar's avatar
ElyKar committed
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
		confFile := args[0]
		fmt.Println("Export user configuration")
		var keyPassphrase, confPassphrase string

		config, err := user.NewConfig(common.SubViper("file_key", "file_cert"))
		if err != nil {
			_, _ = os.Stderr.WriteString(fmt.Sprintf("Couldn't open the files: %s", err))
			os.Exit(1)
			return
		}

		err = readPassphrases(&keyPassphrase, &confPassphrase, true)
		if err != nil {
			_, _ = os.Stderr.WriteString(fmt.Sprintf("An error occurred: %s", err))
			os.Exit(1)
			return
		}

		err = config.SaveConfigToFile(confFile, confPassphrase, keyPassphrase)
		if err != nil {
			_, _ = os.Stderr.WriteString(fmt.Sprintf("Couldn't save the configuration on the disk: %s", err))
			os.Exit(1)
			return
		}
	},
}

// import the configuration
var importCmd = &cobra.Command{
	Use:   "import <c>",
	Short: "import private key and certificate of the user from file c",
	Run: func(cmd *cobra.Command, args []string) {
55 56 57 58 59 60
		if len(args) != 1 {
			_ = cmd.Usage()
			os.Exit(1)
			return
		}

ElyKar's avatar
ElyKar committed
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
		confFile := args[0]
		var keyPassphrase, confPassphrase string
		err := readPassphrases(&keyPassphrase, &confPassphrase, false)
		if err != nil {
			_, _ = os.Stderr.WriteString(fmt.Sprintf("An error occurred: %s", err))
			os.Exit(1)
			return
		}

		config, err := user.DecodeConfiguration(confFile, keyPassphrase, confPassphrase)
		if err != nil {
			_, _ = os.Stderr.WriteString(fmt.Sprintf("Couldnd't decrypt the configuration: %s", err))
			os.Exit(1)
			return
		}

		err = config.SaveUserInformations()
		if err != nil {
			_, _ = os.Stderr.WriteString(fmt.Sprintf("Couldn't save the certificate and private key: %s", err))
			os.Exit(1)
			return
		}
	},
}

// Read two passphrases for the configuration
func readPassphrases(keyPassphrase, confPassphrase *string, second bool) error {
	fmt.Println("Enter the passphrase of the configuration")
	err := readPassword(confPassphrase, second)
	if err != nil {
		return err
	}

	fmt.Println("Enter the passphrase of your current key (if any)")
	return readPassword(keyPassphrase, false)
}