-
Notifications
You must be signed in to change notification settings - Fork 0
/
encrypt.go
98 lines (81 loc) · 2.25 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
90
91
92
93
94
95
96
97
98
package gitage
import (
"bytes"
"context"
"io"
stdfs "io/fs"
"path/filepath"
"filippo.io/age"
"github.com/go-git/go-billy/v5"
"github.com/joanlopez/gitage/internal/fs"
)
// EncryptAll encrypts all files in the specified path,
// so it is equivalent to calling EncryptFile for each
// file in the given path, recursively.
//
// It skips directories (files are encrypted individually)
// and encrypted files (files with the .age extension) to
// avoid double encryption.
//
// Arguments:
// - path: must be an absolute path.
func EncryptAll(ctx context.Context, f billy.Filesystem, path string, recipients ...age.Recipient) error {
return fs.Walk(f, path, func(path string, info stdfs.FileInfo, err error) error {
if err != nil {
return err
}
// Skip directories
if info.IsDir() {
return nil
}
// Skip encrypted files
if filepath.Ext(path) == Ext {
return nil
}
return EncryptFile(ctx, f, path, recipients...)
})
}
// EncryptFile encrypts the file present at the given
// path, within the given file-system, using the given
// recipients.
//
// In comparison to Encrypt, it replaces the plain file
// with the encrypted one (with the .age extension).
//
// So, assuming it can be called with a non-transactional
// file-system, use it with care. An unsuccessful operation
// will leave the file-system in an inconsistent state.
//
// Arguments:
// - path: must be an absolute path.
func EncryptFile(ctx context.Context, f billy.Filesystem, path string, recipients ...age.Recipient) error {
read, err := fs.Read(f, path)
if err != nil {
return err
}
if err = fs.RemoveAll(f, path); err != nil {
return err
}
toWrite, err := Encrypt(ctx, read, recipients...)
if err != nil {
return err
}
agedPath := path + Ext
return fs.Create(f, agedPath, toWrite)
}
// Encrypt encrypts the given plaintext using the given
// recipients and 'age' encryption tool (Go library).
func Encrypt(_ context.Context, plaintext []byte, recipients ...age.Recipient) ([]byte, error) {
buff := new(bytes.Buffer)
w, err := age.Encrypt(buff, recipients...)
if err != nil {
return nil, err
}
if _, err = io.Copy(w, bytes.NewReader(plaintext)); err != nil {
return nil, err
}
if err = w.Close(); err != nil {
return nil, err
}
return buff.Bytes(), nil
}