-
Notifications
You must be signed in to change notification settings - Fork 1
/
crypto.go
88 lines (76 loc) · 1.63 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
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
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())
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return 0, err
}
// pprepent iv to the file
if _, err := dst.Write(iv); err != nil {
return 0, nil
}
stream := cipher.NewCTR(block, iv)
return copyStream(stream, block.BlockSize(), src, dst)
}