/
encrypt.go
182 lines (157 loc) · 4.05 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package crypt
import (
"errors"
"fmt"
"io/fs"
_ "log"
"os"
"path/filepath"
"strings"
"golang.org/x/crypto/ssh/terminal"
)
var c *Cipher
func checkErr(err error) {
if err != nil {
panic(err)
}
}
func Encrypt(password, srcPath, dstPath string, deleteSrc bool) {
if password == "" {
fmt.Printf("Enter password: ")
passwordByte, err := terminal.ReadPassword(int(os.Stdin.Fd()))
password = string(passwordByte)
checkErr(err)
}
fmt.Print("\n")
var err error
c, err = NewCipher(string(password), "")
checkErr(err)
fi, err := os.Stat(srcPath)
checkErr(err)
if fi.IsDir() {
encryptDirectory(srcPath, dstPath, deleteSrc)
} else {
srcPath, err = filepath.Abs(srcPath)
checkErr(err)
os.Chdir(dstPath)
encryptFile(srcPath, deleteSrc)
}
}
func encryptFile(path string, deleteSrc bool) {
data, err := os.ReadFile(path)
checkErr(err)
cipherdata, err := c.encryptData(data)
checkErr(err)
ciphername := c.encryptName(filepath.Base(path))
// Check if the file has already been encrypted by
// a previous run of peasycrypt
fi, err := os.Stat(ciphername)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
err = os.WriteFile(ciphername, cipherdata, 0664)
checkErr(err)
} else {
panic(err)
}
} else {
// Check if the file was finished encrypting in the
// last run. If not, encrypt it again.
plainfi, err := os.Stat(path)
checkErr(err)
if fi.Size() != encryptedSize(plainfi.Size()) {
err = os.WriteFile(ciphername, cipherdata, 0664)
checkErr(err)
}
}
// log.Printf("current file: %v\n", path)
// log.Printf("encrypted name: %v\n", ciphername)
// delete source file after encryption
if deleteSrc {
err = os.Remove(path)
checkErr(err)
}
}
func encryptDirectory(srcPath, dstPath string, deleteSrc bool) {
// rsync style trailing slash
skipRoot := strings.HasSuffix(srcPath, "/")
// Convert to absolute so unaffected by changing cwd's later
srcPath, err := filepath.Abs(srcPath)
checkErr(err)
err = os.Chdir(dstPath)
checkErr(err)
lastDir := ""
err = filepath.WalkDir(srcPath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if srcPath == path && skipRoot {
return nil
}
ciphername := c.encryptName(d.Name())
// log.Printf("current directory: %v\n", path)
// log.Printf("encrypted name: %v\n", ciphername)
// Check if sister or parent of last directory
if lastDir != "" {
rel, err := filepath.Rel(lastDir, path)
checkErr(err)
if strings.HasPrefix(rel, "..") {
// We may have gone back more than one directory. In that case, we
// need to do as much os.Chdir("..") for every .. in the beginning
// of the relative path
var i int
for strings.HasPrefix(rel, "..") {
os.Chdir("..")
// Skip the first three characters which would be ../ and check if
// we have .. again.
i += 3
rel = rel[i:]
}
// We only go back a directory after everything in the last
// directory has been encrypted. So last directory can been
// deleted after we've changed directories
if deleteSrc {
err = os.Remove(lastDir)
checkErr(err)
}
// After changing directories we might land a file and the
// direcotry change will not be detected by the below condition
if !d.IsDir() {
lastDir = filepath.Dir(path)
}
}
}
if d.IsDir() {
lastDir = path
err = os.Mkdir(ciphername, os.ModePerm)
if err != nil && !errors.Is(err, os.ErrExist) {
panic(err)
}
os.Chdir(ciphername)
return nil
}
encryptFile(path, deleteSrc)
return nil
})
checkErr(err)
if deleteSrc {
// Delete directores that were empty after the last iteration of the walk loop,
// but weren't visited again because they were already visited when they had children
if skipRoot {
removeContents(srcPath)
} else {
err = os.RemoveAll(srcPath)
checkErr(err)
}
}
}
func removeContents(dir string) {
d, err := os.Open(dir)
checkErr(err)
defer d.Close()
names, err := d.Readdirnames(0)
checkErr(err)
for _, name := range names {
err = os.RemoveAll(filepath.Join(dir, name))
checkErr(err)
}
}