-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
96 lines (76 loc) · 1.38 KB
/
file.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
package main
import (
"flag"
"fmt"
"io"
"os"
"github.com/k0kubun/go-ansi"
)
func fileExists(filename string) bool {
_, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return err == nil
}
func getFilename() {
filename = flag.Arg(0)
if len(os.Args) == 1 {
fmt.Println("evi: try 'evi -help' for more information")
os.Exit(0)
}
if filename == "" {
ansi.Printf(eviError, "no file specified")
os.Exit(1)
}
}
func decryptFile(fileName string) error {
file, err := os.OpenFile(fileName, os.O_RDWR, 0o644)
if err != nil {
return err
}
defer file.Close()
b, err := io.ReadAll(file)
if err != nil {
return err
}
plainText, err := decryptBytes(b)
if err != nil {
return err
}
if _, err := file.Seek(0, 0); err != nil {
return err
}
if err := file.Truncate(0); err != nil {
return err
}
if _, err := file.Write(plainText); err != nil {
return err
}
return nil
}
func encryptFile(fileName string) error {
file, err := os.OpenFile(fileName, os.O_RDWR, 0o644)
if err != nil {
return err
}
defer file.Close()
b, err := io.ReadAll(file)
if err != nil {
return err
}
encrypted, err := encryptBytes(b)
if err != nil {
return err
}
if _, err := file.Seek(0, 0); err != nil {
return err
}
if err := file.Truncate(0); err != nil {
return err
}
if _, err := file.Write(encrypted); err != nil {
return err
}
return nil
}