-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
329 lines (286 loc) · 7.44 KB
/
main.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
flag "github.com/pborman/getopt"
"go.mongodb.org/mongo-driver/bson"
)
type AESForm struct {
state int
sign int
key []byte
iv []byte
masked_iv []byte
mask []byte
file []byte
}
func (a *AESForm) Decrypt() error {
if a.sign != 0 {
if a.mask == nil {
a.iv = a.file[128 : 128+aes.BlockSize]
} else {
iv, err := IVFromMask(a.mask, a.file[a.sign:a.sign+aes.BlockSize])
if err != nil {
return fmt.Errorf("Decrypt: failed generating IV: %w", err)
} else {
a.iv = iv
}
}
} else {
if a.mask == nil {
a.iv = a.file[:aes.BlockSize]
} else {
iv, err := IVFromMask(a.mask, a.file[:aes.BlockSize])
if err != nil {
return fmt.Errorf("Decrypt: failed generating IV: %w", err)
} else {
a.iv = iv
}
}
}
block, err := aes.NewCipher(a.key)
if err != nil {
return fmt.Errorf("Decrypt: failed creating cipher: %w", err)
}
if len(a.file) < aes.BlockSize {
return fmt.Errorf("Decrypt: ciphertext is too short")
}
var ciphertext []byte
if a.sign != 0 {
ciphertext = a.file[aes.BlockSize+a.sign:]
} else {
ciphertext = a.file[aes.BlockSize:]
}
if len(ciphertext)%aes.BlockSize != 0 {
return fmt.Errorf("Decrypt: ciphertext is not a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, a.iv)
mode.CryptBlocks(ciphertext, ciphertext)
a.file, err = Unpad(ciphertext)
if err != nil {
return fmt.Errorf("Encrypt: failed unpadding file: %w", err)
}
a.state = 1
return nil
}
func (a *AESForm) Encrypt() error {
block, err := aes.NewCipher(a.key)
if err != nil {
return fmt.Errorf("Encrypt: failed creating cipher: %w", err)
}
if len(a.file)%aes.BlockSize != 0 {
a.file, err = Pad(a.file, aes.BlockSize)
if err != nil {
return fmt.Errorf("Encrypt: failed padding file: %w", err)
}
}
if a.mask != nil {
a.masked_iv, err = IVFromMask(a.mask, a.iv)
if err != nil {
return fmt.Errorf("Encrypt: failed masking iv: %w", err)
}
} else {
a.masked_iv = a.iv
}
mode := cipher.NewCBCEncrypter(block, a.iv)
mode.CryptBlocks(a.file, a.file)
if a.sign != 0 {
a.file = []byte(string(a.file[:a.sign]) + string(a.masked_iv) + string(a.file))
} else {
a.file = []byte(string(a.masked_iv) + string(a.file))
}
a.state = 0
return nil
}
func Unpad(src []byte) ([]byte, error) {
l := len(src)
if v := l - int(src[l-1]); v > 0 {
return src[:v], nil
}
return nil, fmt.Errorf("Unpad: unpad value is greater than file size")
}
func Pad(src []byte, multiple int) ([]byte, error) {
if multiple > 255 {
return nil, fmt.Errorf("Pad: multiple must be less than 256")
}
padding := multiple - len(src)%multiple
pad := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, pad...), nil
}
func IVFromMask(mask []byte, block []byte) ([]byte, error) {
var buff []byte
if len(mask) != len(block) {
return nil, fmt.Errorf("IVFromMask: mask size mismatch")
}
for i, v := range block {
buff = append(buff, mask[i]^v)
}
return buff, nil
}
// New() expects strings formatted in hex for the following values:
// key string -> hex.DecodeString -> []byte
// iv string -> hex.DecodeString -> []byte
// mask string -> hex.DecodeString -> []byte
// States:
// 0 (Encrypted) -> Decrypt
// 1 (Decrypted) -> Encrypt
// Where path is the path of the file to be read
func New(state int, sign int, path string, key string, iv string, mask string) (AESForm, error) {
var par AESForm
file, err := ioutil.ReadFile(path)
if err != nil {
return par, fmt.Errorf("New: failed reading file: %w", err)
} else {
par.file = file
}
if mask != "" {
bMask, err := hex.DecodeString(mask)
if err != nil {
return par, fmt.Errorf("New: failed decoding hex: %w", err)
} else {
par.mask = bMask
}
}
if iv != "" {
bIV, err := hex.DecodeString(iv)
if err != nil || len(bIV) != aes.BlockSize {
return par, fmt.Errorf("New: failed decoding hex: %w", err)
} else {
par.iv = bIV
if state == 0 {
par.file = append(par.iv, par.file...)
}
}
} else {
bytes := make([]byte, aes.BlockSize)
if _, err := rand.Read(bytes); err != nil {
log.Fatalf("New: failed generating bytes: %s", err)
}
par.iv = bytes
}
bKey, err := hex.DecodeString(key)
if err != nil {
return par, fmt.Errorf("New: failed decoding hex: %w", err)
}
par.state = state
par.key = bKey
par.sign = sign
return par, nil
}
func main() {
var (
help = false
state = -1
sign = 0
bson = 0
key = ""
input = ""
output = "~/out.bin"
mask = ""
iv = ""
)
flag.BoolVarLong(&help, "help", 'h', "displays help")
flag.IntVarLong(&state, "state", 's', "Whether the data is encrypted (0) or decrypted (1)", "int")
flag.IntVarLong(&bson, "bson", 'b', "Whether to enable bson output fix (1) or not (0)", "int")
flag.IntVarLong(&sign, "index", 'n', "Index of data encrypted with sign", "int")
flag.StringVarLong(&key, "key", 'k', "The input file", "str")
flag.StringVarLong(&input, "input", 'i', "The input file", "str")
flag.StringVarLong(&output, "output", 'o', "The output file path", "str")
flag.StringVarLong(&mask, "mask", 'm', "The AES mask in hexadecimal (Optional)", "str")
flag.StringVarLong(&iv, "vect", 'v', "The AES init vector in hexadecimal (Optional)", "str")
flag.Parse()
if help {
flag.Usage()
os.Exit(0)
}
log.Printf("Key: '%s'", key)
log.Printf("Mask: '%s'", mask)
log.Printf("IV: '%s'", iv)
log.Printf("State: %s", fmt.Sprint(state))
log.Printf("In: '%s'", input)
log.Printf("Out: '%s'", output)
if key == "" {
log.Fatal("main: missing key!")
}
if state == -1 {
log.Fatal("main: please specify state!")
}
if input == "" {
log.Fatal("main: output file required")
}
a, err := New(state, sign, input, key, iv, mask)
if err != nil {
log.Fatalf("main: failed parsing data: %s", err)
} else {
switch a.state {
case 0:
err = a.Decrypt()
if err != nil {
log.Fatalf("main: failed decrypting data: %s", err)
} else {
log.Print("Successfully decrypted file...")
}
if bson == 1 {
a.BsonMarshal()
}
case 1:
if bson == 1 {
a.BsonUnmarshal()
}
err = a.Encrypt()
if err != nil {
log.Fatalf("main: failed encrypting data: %s", err)
} else {
log.Print("Successfully encrypted file...")
}
default:
log.Fatal("main: invalid state!")
}
}
out, err := os.Create(output)
if err != nil {
log.Fatalf("main: failed creating file: %s", err)
}
defer out.Close()
_, err = out.Write(a.file)
if err != nil {
log.Fatalf("main: failed writing file: %s", err)
}
}
// If you are using this to decrypt Arknights data, then the below function
// can be used to convert BSON data to JSON for viewability, make sure to set the sign to 128.
func (a *AESForm) BsonMarshal() error {
var raw bson.Raw = a.file
mp := make(map[string]interface{})
err := bson.Unmarshal(raw, &mp)
if err != nil {
return fmt.Errorf("TestMarshal: failed unmarshalling bson: %w", err)
}
data, err := json.Marshal(mp)
if err != nil {
return fmt.Errorf("TestMarshal: failed marshalling to json: %w", err)
}
a.file = data
return nil
}
func (a *AESForm) BsonUnmarshal() error {
mp := make(map[string]interface{})
err := json.Unmarshal(a.file, &mp)
if err != nil {
return fmt.Errorf("TestUnmarshal: failed unmarshalling json: %w", err)
}
data, err := bson.Marshal(mp)
if err != nil {
return fmt.Errorf("TestUnmarshal: failed marshalling to bson: %w", err)
}
a.file = data
return nil
}