/
gpgencryption.go
78 lines (69 loc) · 1.91 KB
/
gpgencryption.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
package chezmoi
import (
"bytes"
"os"
"os/exec"
"github.com/rs/zerolog/log"
"github.com/twpayne/chezmoi/chezmoi2/internal/chezmoilog"
)
// A GPGEncryption uses gpg for encryption and decryption. See https://gnupg.org/.
type GPGEncryption struct {
Command string
Args []string
Recipient string
Symmetric bool
}
// Decrypt implements Encyrption.Decrypt.
func (t *GPGEncryption) Decrypt(ciphertext []byte) ([]byte, error) {
args := append([]string{"--decrypt"}, t.Args...)
//nolint:gosec
cmd := exec.Command(t.Command, args...)
cmd.Stdin = bytes.NewReader(ciphertext)
return chezmoilog.LogCmdOutput(log.Logger, cmd)
}
// DecryptToFile implements Encryption.DecryptToFile.
func (t *GPGEncryption) DecryptToFile(filename string, ciphertext []byte) error {
args := append([]string{
"--decrypt",
"--output", filename,
"--yes",
}, t.Args...)
//nolint:gosec
cmd := exec.Command(t.Command, args...)
cmd.Stdin = bytes.NewReader(ciphertext)
return chezmoilog.LogCmdRun(log.Logger, cmd)
}
// Encrypt implements Encryption.Encrypt.
func (t *GPGEncryption) Encrypt(plaintext []byte) ([]byte, error) {
args := append(t.encryptArgs(), t.Args...)
//nolint:gosec
cmd := exec.Command(t.Command, args...)
cmd.Stdin = bytes.NewReader(plaintext)
return chezmoilog.LogCmdOutput(log.Logger, cmd)
}
// EncryptFile implements Encryption.EncryptFile.
func (t *GPGEncryption) EncryptFile(filename string) (ciphertext []byte, err error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
args := append(t.encryptArgs(), t.Args...)
//nolint:gosec
cmd := exec.Command(t.Command, args...)
cmd.Stdin = f
return chezmoilog.LogCmdOutput(log.Logger, cmd)
}
func (t *GPGEncryption) encryptArgs() []string {
args := []string{
"--armor",
"--encrypt",
}
if t.Recipient != "" {
args = append(args, "--recipient", t.Recipient)
}
if t.Symmetric {
args = append(args, "--symmetric")
}
return args
}