-
Notifications
You must be signed in to change notification settings - Fork 1
/
encrypt.go
58 lines (51 loc) · 1.04 KB
/
encrypt.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
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
"log"
"os"
)
func EncryptFile(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)
}
nonce := make([]byte, block.BlockSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
log.Fatal(err)
}
outfileName := setFilename(targetFilename, "encrypt")
outfile, err := os.OpenFile(outfileName, os.O_RDWR|os.O_CREATE, 0777)
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 {
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
}
}
// Append the nonce
outfile.Write(nonce)
return outfileName
}