-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
85 lines (71 loc) · 1.55 KB
/
crypto.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
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"io"
)
func hashKey(key string) string {
hash := md5.Sum([]byte(key))
return hex.EncodeToString(hash[:])
}
func newEncryptionKey() []byte {
keyBuf := make([]byte, 32)
io.ReadFull(rand.Reader, keyBuf)
return keyBuf
}
func copyStream(stream cipher.Stream, blockSize int, src io.Reader, dest io.Writer) (int, error) {
var (
buf = make([]byte, 32*1024)
nw = blockSize
)
for {
n, err := src.Read(buf)
if n > 0 {
stream.XORKeyStream(buf, buf[:n])
nn, err := dest.Write(buf[:n])
if err != nil {
return 0, err
}
nw += nn
}
if err == io.EOF {
break
}
if err != nil {
return 0, err
}
}
return nw, nil
}
func copyEncrypt(key []byte, src io.Reader, dest io.Writer) (int, error) {
block, err := aes.NewCipher(key)
if err != nil {
return 0, err
}
iv := make([]byte, block.BlockSize())
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return 0, err
}
// prepend the IV to the file
if _, err := dest.Write(iv); err != nil {
return 0, err
}
stream := cipher.NewCTR(block, iv)
return copyStream(stream, block.BlockSize(), src, dest)
}
func copyDecrypt(key []byte, src io.Reader, dest io.Writer) (int, error) {
block, err := aes.NewCipher(key)
if err != nil {
return 0, err
}
// Read IV from the given io.Reader
iv := make([]byte, block.BlockSize())
if _, err := src.Read(iv); err != nil {
return 0, err
}
stream := cipher.NewCTR(block, iv)
return copyStream(stream, block.BlockSize(), src, dest)
}