You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/transport/internet/kcp/crypt.go

79 lines
1.7 KiB

// +build !confonly
package kcp
import (
"crypto/cipher"
"encoding/binary"
"hash/fnv"
7 years ago
"v2ray.com/core/common"
)
8 years ago
// SimpleAuthenticator is a legacy AEAD used for KCP encryption.
type SimpleAuthenticator struct{}
8 years ago
// NewSimpleAuthenticator creates a new SimpleAuthenticator
func NewSimpleAuthenticator() cipher.AEAD {
return &SimpleAuthenticator{}
}
8 years ago
// NonceSize implements cipher.AEAD.NonceSize().
8 years ago
func (*SimpleAuthenticator) NonceSize() int {
return 0
}
8 years ago
// Overhead implements cipher.AEAD.NonceSize().
8 years ago
func (*SimpleAuthenticator) Overhead() int {
return 6
}
8 years ago
// Seal implements cipher.AEAD.Seal().
8 years ago
func (a *SimpleAuthenticator) Seal(dst, nonce, plain, extra []byte) []byte {
dst = append(dst, 0, 0, 0, 0, 0, 0) // 4 bytes for hash, and then 2 bytes for length
binary.BigEndian.PutUint16(dst[4:], uint16(len(plain)))
dst = append(dst, plain...)
fnvHash := fnv.New32a()
7 years ago
common.Must2(fnvHash.Write(dst[4:]))
fnvHash.Sum(dst[:0])
dstLen := len(dst)
xtra := 4 - dstLen%4
if xtra != 4 {
dst = append(dst, make([]byte, xtra)...)
}
xorfwd(dst)
if xtra != 4 {
dst = dst[:dstLen]
}
return dst
}
8 years ago
// Open implements cipher.AEAD.Open().
8 years ago
func (a *SimpleAuthenticator) Open(dst, nonce, cipherText, extra []byte) ([]byte, error) {
dst = append(dst, cipherText...)
dstLen := len(dst)
xtra := 4 - dstLen%4
if xtra != 4 {
dst = append(dst, make([]byte, xtra)...)
}
xorbkd(dst)
if xtra != 4 {
dst = dst[:dstLen]
}
fnvHash := fnv.New32a()
7 years ago
common.Must2(fnvHash.Write(dst[4:]))
if binary.BigEndian.Uint32(dst[:4]) != fnvHash.Sum32() {
return nil, newError("invalid auth")
}
length := binary.BigEndian.Uint16(dst[4:6])
if len(dst)-6 != int(length) {
return nil, newError("invalid auth")
}
return dst[6:], nil
}