-
Notifications
You must be signed in to change notification settings - Fork 43
/
backup.go
97 lines (79 loc) · 1.83 KB
/
backup.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
package backup
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/json"
"errors"
"io"
"io/ioutil"
)
type Backup struct {
PrivateKey string `json:"privateKey"`
}
// Note: Using static key since the goal of this is to obfuscate the file, not to encrypt it
var key = []byte{0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC, 0xBC}
func obfuscate(data []byte) ([]byte, error) {
block, err := aes.NewCipher(key[:])
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, data, nil), nil
}
func deobfuscate(ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key[:])
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
if len(ciphertext) < gcm.NonceSize() {
return nil, errors.New("malformed ciphertext")
}
return gcm.Open(nil,
ciphertext[:gcm.NonceSize()],
ciphertext[gcm.NonceSize():],
nil,
)
}
// Creates a backup file in the given path
func MarshalBackup(path string, b *Backup) error {
jsonData, err := json.Marshal(b)
if err != nil {
return err
}
obfuscatedBackup, err := obfuscate(jsonData)
if err != nil {
return err
}
err = ioutil.WriteFile(path, obfuscatedBackup, 0644)
return err
}
// Reads a file in the given path and returns a Backup object
func UnmarshalBackup(path string) (*Backup, error) {
obfuscatedBackup, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
jsonData, err := deobfuscate(obfuscatedBackup)
if err != nil {
return nil, err
}
var result Backup
err = json.Unmarshal(jsonData, &result)
if err != nil {
return nil, err
}
return &result, nil
}