-
Notifications
You must be signed in to change notification settings - Fork 233
/
aes_ctr.go
68 lines (58 loc) · 1.33 KB
/
aes_ctr.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
package osscrypto
import (
"crypto/aes"
"crypto/cipher"
"io"
)
type aesCtr struct {
encrypter cipher.Stream
decrypter cipher.Stream
}
func newAesCtr(cd CipherData) (Cipher, error) {
block, err := aes.NewCipher(cd.Key)
if err != nil {
return nil, err
}
encrypter := cipher.NewCTR(block, cd.IV)
decrypter := cipher.NewCTR(block, cd.IV)
return &aesCtr{encrypter, decrypter}, nil
}
func (c *aesCtr) Encrypt(src io.Reader) io.Reader {
reader := &ctrEncryptReader{
encrypter: c.encrypter,
src: src,
}
return reader
}
type ctrEncryptReader struct {
encrypter cipher.Stream
src io.Reader
}
func (reader *ctrEncryptReader) Read(data []byte) (int, error) {
plainText := make([]byte, len(data), len(data))
n, err := reader.src.Read(plainText)
if n > 0 {
plainText = plainText[0:n]
reader.encrypter.XORKeyStream(data, plainText)
}
return n, err
}
func (c *aesCtr) Decrypt(src io.Reader) io.Reader {
return &ctrDecryptReader{
decrypter: c.decrypter,
src: src,
}
}
type ctrDecryptReader struct {
decrypter cipher.Stream
src io.Reader
}
func (reader *ctrDecryptReader) Read(data []byte) (int, error) {
cryptoText := make([]byte, len(data), len(data))
n, err := reader.src.Read(cryptoText)
if n > 0 {
cryptoText = cryptoText[0:n]
reader.decrypter.XORKeyStream(data, cryptoText)
}
return n, err
}