forked from ToyoDAdoubi/brook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cipher.go
80 lines (68 loc) · 1.74 KB
/
cipher.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
package brook
import (
"crypto/aes"
"crypto/cipher"
"errors"
"net"
"time"
"github.com/txthinking/ant"
)
// CipherConn is the encrypted connection
type CipherConn struct {
c net.Conn
sr cipher.StreamReader
sw cipher.StreamWriter
}
// NewCipherConn returns a new CipherConn, iv length must be equal aes.BlockSize
func NewCipherConn(c net.Conn, key []byte, iv []byte) (*CipherConn, error) {
if len(iv) != aes.BlockSize {
return nil, errors.New("Invalid IV length")
}
block, err := aes.NewCipher(ant.AESMake256Key(key))
if err != nil {
return nil, err
}
return &CipherConn{
c: c,
sr: cipher.StreamReader{
S: cipher.NewCFBDecrypter(block, iv),
R: c,
},
sw: cipher.StreamWriter{
S: cipher.NewCFBEncrypter(block, iv),
W: c,
},
}, nil
}
// Read is just like net.Conn interface
func (c *CipherConn) Read(b []byte) (n int, err error) {
return c.sr.Read(b)
}
// Write is just like net.Conn interface
func (c *CipherConn) Write(b []byte) (n int, err error) {
return c.sw.Write(b)
}
// Close is just like net.Conn interface
func (c *CipherConn) Close() error {
return c.c.Close()
}
// LocalAddr is just like net.Conn interface
func (c *CipherConn) LocalAddr() net.Addr {
return c.c.LocalAddr()
}
// RemoteAddr is just like net.Conn interface
func (c *CipherConn) RemoteAddr() net.Addr {
return c.c.RemoteAddr()
}
// SetDeadline is just like net.Conn interface
func (c *CipherConn) SetDeadline(t time.Time) error {
return c.c.SetDeadline(t)
}
// SetReadDeadline is just like net.Conn interface
func (c *CipherConn) SetReadDeadline(t time.Time) error {
return c.c.SetReadDeadline(t)
}
// SetWriteDeadline is just like net.Conn interface
func (c *CipherConn) SetWriteDeadline(t time.Time) error {
return c.c.SetWriteDeadline(t)
}