2022-10-06 14:47:11 +00:00
|
|
|
package shadowtls
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/hmac"
|
|
|
|
"crypto/sha1"
|
|
|
|
"hash"
|
|
|
|
"net"
|
|
|
|
)
|
|
|
|
|
|
|
|
type HashReadConn struct {
|
|
|
|
net.Conn
|
|
|
|
hmac hash.Hash
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewHashReadConn(conn net.Conn, password string) *HashReadConn {
|
|
|
|
return &HashReadConn{
|
|
|
|
conn,
|
|
|
|
hmac.New(sha1.New, []byte(password)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *HashReadConn) Read(b []byte) (n int, err error) {
|
|
|
|
n, err = c.Conn.Read(b)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
_, err = c.hmac.Write(b[:n])
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *HashReadConn) Sum() []byte {
|
|
|
|
return c.hmac.Sum(nil)[:8]
|
|
|
|
}
|
|
|
|
|
|
|
|
type HashWriteConn struct {
|
|
|
|
net.Conn
|
2022-11-22 14:11:09 +00:00
|
|
|
hmac hash.Hash
|
|
|
|
hasContent bool
|
|
|
|
lastSum []byte
|
2022-10-06 14:47:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewHashWriteConn(conn net.Conn, password string) *HashWriteConn {
|
|
|
|
return &HashWriteConn{
|
2022-11-22 14:11:09 +00:00
|
|
|
Conn: conn,
|
|
|
|
hmac: hmac.New(sha1.New, []byte(password)),
|
2022-10-06 14:47:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *HashWriteConn) Write(p []byte) (n int, err error) {
|
|
|
|
if c.hmac != nil {
|
2022-11-22 14:11:09 +00:00
|
|
|
if c.hasContent {
|
|
|
|
c.lastSum = c.Sum()
|
|
|
|
}
|
2022-10-06 14:47:11 +00:00
|
|
|
c.hmac.Write(p)
|
2022-11-22 14:11:09 +00:00
|
|
|
c.hasContent = true
|
2022-10-06 14:47:11 +00:00
|
|
|
}
|
|
|
|
return c.Conn.Write(p)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *HashWriteConn) Sum() []byte {
|
|
|
|
return c.hmac.Sum(nil)[:8]
|
|
|
|
}
|
|
|
|
|
2022-11-22 14:11:09 +00:00
|
|
|
func (c *HashWriteConn) LastSum() []byte {
|
|
|
|
return c.lastSum
|
|
|
|
}
|
|
|
|
|
2022-10-06 14:47:11 +00:00
|
|
|
func (c *HashWriteConn) Fallback() {
|
|
|
|
c.hmac = nil
|
|
|
|
}
|
2022-11-22 14:11:09 +00:00
|
|
|
|
|
|
|
func (c *HashWriteConn) HasContent() bool {
|
|
|
|
return c.hasContent
|
|
|
|
}
|