-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecrypt.go
104 lines (86 loc) · 2.31 KB
/
decrypt.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
99
100
101
102
103
104
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"
)
// DecryptAll decrypts all files in the specified path,
// so it is equivalent to calling DecryptFile for each
// file in the given path, recursively.
//
// It skips directories (files are decrypted individually)
// and non-encrypted files (files without the .age extension)
// to avoid double decryption.
//
// Arguments:
// - path: must be an absolute path.
func DecryptAll(ctx context.Context, f billy.Filesystem, path string, identities ...age.Identity) 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 non-encrypted files
if filepath.Ext(path) != Ext {
return nil
}
err = DecryptFile(ctx, f, path, identities...)
if err != nil {
return err
}
return nil
})
}
// DecryptFile decrypts the file present at the given
// path, within the given file-system, using the given
// identities.
//
// In comparison to Decrypt, it replaces the ciphered
// file with the decrypted one (w/out 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 DecryptFile(ctx context.Context, f billy.Filesystem, path string, identities ...age.Identity) error {
read, err := fs.Read(f, path)
if err != nil {
return err
}
if err = fs.RemoveAll(f, path); err != nil {
return err
}
toWrite, err := Decrypt(ctx, read, identities...)
if err != nil {
return err
}
path = path[:len(path)-len(Ext)]
err = fs.Create(f, path, toWrite)
if err != nil {
return err
}
return nil
}
// Decrypt decrypts the given ciphertext using the given
// recipients and 'age' encryption tool (Go library).
func Decrypt(_ context.Context, ciphertext []byte, identities ...age.Identity) ([]byte, error) {
buff := new(bytes.Buffer)
r, err := age.Decrypt(bytes.NewReader(ciphertext), identities...)
if err != nil {
return nil, err
}
if _, err = io.Copy(buff, r); err != nil {
return nil, err
}
return buff.Bytes(), nil
}