-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdecrypt.go
More file actions
76 lines (59 loc) · 1.31 KB
/
decrypt.go
File metadata and controls
76 lines (59 loc) · 1.31 KB
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
package main
import (
"fmt"
"log"
"strconv"
"time"
)
const (
headerLen = 16
signature = "5250474d56000000"
version = "000301"
remain = "0000000000"
)
func decryptFile(filePath, outPath string, key []byte) error {
start := time.Now()
content, err := readFileContents(filePath)
if err != nil {
log.Fatal(err)
}
if len(content) < headerLen*2 {
return fmt.Errorf("file is too small")
}
if !checkFakeHeader(content[:headerLen]) {
return fmt.Errorf("invalid header")
}
content = content[headerLen:]
if len(content) < 1 {
return fmt.Errorf("file without header is too small")
}
for i := 0; i < headerLen; i++ {
content[i] = content[i] ^ key[i]
}
err = writeFileContents(outPath, &content)
if err != nil {
return err
}
fmt.Printf("decrypted in %s\n", time.Since(start))
return nil
}
func checkFakeHeader(header []byte) bool {
refBytes := make([]byte, headerLen)
refStr := signature + version + remain
// Generate reference bytes
for i := 0; i < headerLen; i++ {
subStrStart := i * 2
num, err := strconv.ParseInt(refStr[subStrStart:subStrStart+2], 16, 32)
if err != nil {
log.Fatal(err)
}
refBytes[i] = byte(num)
}
// Verify header (Check if its an encrypted file)
for i := 0; i < headerLen; i++ {
if refBytes[i] != header[i] {
return false
}
}
return true
}