v2ray-core/transport/internet/kcp/crypt.go

76 lines
1.6 KiB
Go
Raw Normal View History

2016-06-14 21:25:06 +00:00
package kcp
2016-06-17 14:51:41 +00:00
import (
2016-12-08 15:27:41 +00:00
"crypto/cipher"
2016-06-17 14:51:41 +00:00
"hash/fnv"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/common/serial"
2016-12-08 15:27:41 +00:00
)
2016-12-08 15:32:53 +00:00
// SimpleAuthenticator is a legacy AEAD used for KCP encryption.
2016-06-17 14:51:41 +00:00
type SimpleAuthenticator struct{}
2016-12-08 15:32:53 +00:00
// NewSimpleAuthenticator creates a new SimpleAuthenticator
2016-12-08 15:27:41 +00:00
func NewSimpleAuthenticator() cipher.AEAD {
2016-06-17 14:51:41 +00:00
return &SimpleAuthenticator{}
2016-06-14 21:25:06 +00:00
}
2016-12-08 15:32:53 +00:00
// NonceSize implements cipher.AEAD.NonceSize().
2017-04-13 20:17:58 +00:00
func (*SimpleAuthenticator) NonceSize() int {
2016-12-08 15:27:41 +00:00
return 0
}
2016-12-08 15:32:53 +00:00
// Overhead implements cipher.AEAD.NonceSize().
2017-04-13 20:17:58 +00:00
func (*SimpleAuthenticator) Overhead() int {
2016-06-17 14:51:41 +00:00
return 6
2016-06-14 21:25:06 +00:00
}
2016-12-08 15:32:53 +00:00
// Seal implements cipher.AEAD.Seal().
2017-04-13 20:17:58 +00:00
func (a *SimpleAuthenticator) Seal(dst, nonce, plain, extra []byte) []byte {
2016-12-08 15:27:41 +00:00
dst = append(dst, 0, 0, 0, 0)
dst = serial.Uint16ToBytes(uint16(len(plain)), dst)
dst = append(dst, plain...)
2016-06-17 14:51:41 +00:00
fnvHash := fnv.New32a()
2016-12-08 15:27:41 +00:00
fnvHash.Write(dst[4:])
fnvHash.Sum(dst[:0])
2016-06-17 14:51:41 +00:00
2016-12-08 15:27:41 +00:00
len := len(dst)
xtra := 4 - len%4
2016-12-08 15:27:41 +00:00
if xtra != 4 {
dst = append(dst, make([]byte, xtra)...)
}
2016-12-08 15:27:41 +00:00
xorfwd(dst)
if xtra != 4 {
dst = dst[:len]
2016-06-17 14:51:41 +00:00
}
2016-12-08 15:27:41 +00:00
return dst
2016-06-14 21:25:06 +00:00
}
2016-12-08 15:32:53 +00:00
// Open implements cipher.AEAD.Open().
2017-04-13 20:17:58 +00:00
func (a *SimpleAuthenticator) Open(dst, nonce, cipherText, extra []byte) ([]byte, error) {
2016-12-08 15:27:41 +00:00
dst = append(dst, cipherText...)
dstLen := len(dst)
xtra := 4 - dstLen%4
if xtra != 4 {
dst = append(dst, make([]byte, xtra)...)
}
2016-12-08 15:27:41 +00:00
xorbkd(dst)
if xtra != 4 {
dst = dst[:dstLen]
2016-06-17 14:51:41 +00:00
}
fnvHash := fnv.New32a()
2016-12-08 15:27:41 +00:00
fnvHash.Write(dst[4:])
if serial.BytesToUint32(dst[:4]) != fnvHash.Sum32() {
2017-04-09 13:04:04 +00:00
return nil, newError("invalid auth")
2016-06-17 14:51:41 +00:00
}
2016-12-08 15:27:41 +00:00
length := serial.BytesToUint16(dst[4:6])
if len(dst)-6 != int(length) {
2017-04-09 13:04:04 +00:00
return nil, newError("invalid auth")
2016-06-17 14:51:41 +00:00
}
2016-12-08 15:27:41 +00:00
return dst[6:], nil
2016-06-17 14:51:41 +00:00
}