|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + |
| 7 | + "github.com/jonasvinther/medusa/pkg/encrypt" |
| 8 | + "github.com/jonasvinther/medusa/pkg/vaultengine" |
| 9 | + "github.com/spf13/cobra" |
| 10 | +) |
| 11 | + |
| 12 | +func init() { |
| 13 | + rootCmd.AddCommand(encryptCmd) |
| 14 | + encryptCmd.PersistentFlags().StringP("output", "o", "", "Write to file instead of stdout") |
| 15 | + encryptCmd.PersistentFlags().StringP("public-key", "p", "", "Location of the RSA public key") |
| 16 | +} |
| 17 | + |
| 18 | +var encryptCmd = &cobra.Command{ |
| 19 | + Use: "encrypt [file path] [flags]", |
| 20 | + Short: "Encrypt a Vault export file onto stdout or to an output file", |
| 21 | + Long: ``, |
| 22 | + Args: cobra.ExactArgs(1), |
| 23 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 24 | + file := args[0] |
| 25 | + publicKey, _ := cmd.Flags().GetString("public-key") |
| 26 | + output, _ := cmd.Flags().GetString("output") |
| 27 | + |
| 28 | + data, err := os.ReadFile(file) |
| 29 | + if err != nil { |
| 30 | + fmt.Println(err) |
| 31 | + return err |
| 32 | + } |
| 33 | + |
| 34 | + encryptedKey, encryptedData := encrypt.Encrypt(publicKey, output, data) |
| 35 | + |
| 36 | + if output == "" { |
| 37 | + fmt.Println(string([]byte(encryptedData))) |
| 38 | + fmt.Println(string(encryptedKey)) |
| 39 | + } else { |
| 40 | + // Write to file |
| 41 | + // First encrypted data |
| 42 | + err = vaultengine.WriteToFile(output, []byte(encryptedData)) |
| 43 | + if err != nil { |
| 44 | + return err |
| 45 | + } |
| 46 | + err = vaultengine.AppendStringToFile(output, "\n") |
| 47 | + if err != nil { |
| 48 | + return err |
| 49 | + } |
| 50 | + // Then encrypted AES key |
| 51 | + err = vaultengine.AppendStringToFile(output, encryptedKey) |
| 52 | + if err != nil { |
| 53 | + return err |
| 54 | + } |
| 55 | + err = vaultengine.AppendStringToFile(output, "\n") |
| 56 | + if err != nil { |
| 57 | + return err |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return nil |
| 62 | + }, |
| 63 | +} |
0 commit comments