-
Notifications
You must be signed in to change notification settings - Fork 3
/
encrypt.go
89 lines (72 loc) · 2.18 KB
/
encrypt.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
package cmd
import (
"bytes"
"fmt"
"io"
"os"
"github.com/spf13/cobra"
"github.com/capeprivacy/cli/sdk"
)
var encryptCmd = &cobra.Command{
Use: "encrypt",
Short: "Encrypt data.",
Long: "Encrypt input data, takes data as the first and only argument.\n" +
"Encrypt can also read input data from stdin, example: \"echo '1234' | cape encrypt\".\n" +
"Encrypt can also read a file, example: \"echo 'Hello!' > example.txt; cape encrypt -f ./example.txt\".\n" +
"Results are output to stdout so you can easily pipe them elsewhere.",
RunE: encrypt,
}
func init() {
rootCmd.AddCommand(encryptCmd)
encryptCmd.PersistentFlags().StringP("file", "f", "", "input data file")
encryptCmd.PersistentFlags().StringSliceP("pcr", "p", []string{""}, "pass multiple PCRs to validate against, used while getting key for the first time")
}
func encrypt(cmd *cobra.Command, args []string) error {
pcrSlice, err := cmd.Flags().GetStringSlice("pcr")
if err != nil {
return UserError{Msg: "error retrieving pcr flags", Err: err}
}
input, userError := parseInput(cmd, args)
if userError != nil {
return userError
}
keyReq, err := GetKeyRequest(pcrSlice)
if err != nil {
return err
}
result, err := sdk.Encrypt(keyReq, input)
if err != nil {
return err
}
fmt.Println(result)
return nil
}
func parseInput(cmd *cobra.Command, args []string) ([]byte, *UserError) {
if len(args) > 1 {
return nil, &UserError{Msg: "you must pass in only one input data (stdin, string or filename)", Err: fmt.Errorf("invalid number of input arguments")}
}
var input []byte
file, err := cmd.Flags().GetString("file")
if err != nil {
return nil, &UserError{Msg: "error retrieving file flag", Err: err}
}
switch {
case file != "":
// input file was provided
input, err = os.ReadFile(file)
if err != nil {
return nil, &UserError{Msg: "unable to read data file", Err: err}
}
case len(args) == 1:
// read input from command line string
input = []byte(args[0])
default:
// read input from stdin
buf := new(bytes.Buffer)
if _, err := io.Copy(buf, cmd.InOrStdin()); err != nil {
return nil, &UserError{Msg: "unable to read data from stdin", Err: err}
}
input = buf.Bytes()
}
return input, nil
}