-
Notifications
You must be signed in to change notification settings - Fork 1
/
decrypt.go
67 lines (59 loc) · 1.22 KB
/
decrypt.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
package main
import (
"crypto/aes"
"crypto/cipher"
"io"
"log"
"os"
)
func DecryptFile(targetFilename string, key []byte) string {
infile, err := os.Open(targetFilename)
if err != nil {
log.Fatal(err)
}
defer infile.Close()
block, err := aes.NewCipher(key)
if err != nil {
log.Panic(err)
}
fi, err := infile.Stat()
if err != nil {
log.Fatal(err)
}
nonce := make([]byte, block.BlockSize())
msgLen := fi.Size() - int64(len(nonce))
_, err = infile.ReadAt(nonce, msgLen)
if err != nil {
log.Fatal(err)
}
outfileName := setFilename(targetFilename, "decrypt")
outfile, err := os.OpenFile(outfileName, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
log.Fatal(err)
}
defer outfile.Close()
// The buffer size must be multiple of 16 bytes
buf := make([]byte, 1024)
stream := cipher.NewCTR(block, nonce)
for {
n, err := infile.Read(buf)
if n > 0 {
// The last bytes are the nonce, don't belong the original message
if n > int(msgLen) {
n = int(msgLen)
}
msgLen -= int64(n)
stream.XORKeyStream(buf, buf[:n])
// Write into file
outfile.Write(buf[:n])
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("Read %d bytes: %v", n, err)
break
}
}
return outfileName
}