-
Notifications
You must be signed in to change notification settings - Fork 2
/
chacha20_stream.go
executable file
·48 lines (38 loc) · 783 Bytes
/
chacha20_stream.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
package crypto
import (
"crypto/cipher"
"io"
"golang.org/x/crypto/chacha20"
)
type ChaCha20Stream struct {
source io.Reader
stream cipher.Stream
}
func (cs *ChaCha20Stream) Read(p []byte) (int, error) {
n, err := cs.source.Read(p)
if err != nil {
return n, err
}
if n == 0 || err == io.EOF {
return n, io.EOF
}
cs.stream.XORKeyStream(p[:n], p[:n])
return n, nil
}
func (cs *ChaCha20Stream) Close() error {
if rc, ok := cs.source.(io.ReadCloser); ok {
return rc.Close()
}
return nil
}
func NewChaCha20Stream(r io.Reader, key []byte) (*ChaCha20Stream, error) {
nonce := make([]byte, 24)
stream, err := chacha20.NewUnauthenticatedCipher(key, nonce)
if err != nil {
return nil, err
}
return &ChaCha20Stream{
source: r,
stream: stream,
}, nil
}