-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
93 lines (77 loc) · 1.74 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
86
87
88
89
90
91
92
93
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"io"
)
func generateID() string {
buf := make([]byte, 32)
io.ReadFull(rand.Reader, buf)
return hex.EncodeToString(buf)
}
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, dst 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 := dst.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 copyDecrypt(key []byte, src io.Reader, dst io.Writer) (int, error) {
block, err := aes.NewCipher(key)
if err != nil {
return 0, err
}
// Read the IV from the given io.Reader which in our case should be
// the block.BlockSize() bytes we read.
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, dst)
}
func copyEncrypt(key []byte, src io.Reader, dst io.Writer) (int, error) {
block, err := aes.NewCipher(key)
if err != nil {
return 0, err
}
iv := make([]byte, block.BlockSize()) // 16 bytes ?
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return 0, err
}
// prepend the IV to the file.
if _, err := dst.Write(iv); err != nil {
return 0, err
}
stream := cipher.NewCTR(block, iv)
return copyStream(stream, block.BlockSize(), src, dst)
}