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/proxy/vmess/encoding/auth.go

75 lines
1.8 KiB

package encoding
import (
"crypto/md5"
8 years ago
"errors"
8 years ago
"hash/fnv"
8 years ago
"v2ray.com/core/common/serial"
)
8 years ago
// Authenticate authenticates a byte array using Fnv hash.
func Authenticate(b []byte) uint32 {
fnv1hash := fnv.New32a()
fnv1hash.Write(b)
return fnv1hash.Sum32()
}
type NoOpAuthenticator struct{}
func (NoOpAuthenticator) NonceSize() int {
return 0
}
func (NoOpAuthenticator) Overhead() int {
return 0
}
// Seal implements AEAD.Seal().
func (NoOpAuthenticator) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
return append(dst[:0], plaintext...)
}
// Open implements AEAD.Open().
func (NoOpAuthenticator) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
return append(dst[:0], ciphertext...), nil
}
8 years ago
// FnvAuthenticator is an AEAD based on Fnv hash.
type FnvAuthenticator struct {
}
8 years ago
// NonceSize implements AEAD.NonceSize().
func (v *FnvAuthenticator) NonceSize() int {
return 0
}
8 years ago
// Overhead impelements AEAD.Overhead().
func (v *FnvAuthenticator) Overhead() int {
return 4
}
8 years ago
// Seal implements AEAD.Seal().
func (v *FnvAuthenticator) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
8 years ago
dst = serial.Uint32ToBytes(Authenticate(plaintext), dst)
return append(dst, plaintext...)
}
8 years ago
// Open implements AEAD.Open().
func (v *FnvAuthenticator) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
if serial.BytesToUint32(ciphertext[:4]) != Authenticate(ciphertext[4:]) {
8 years ago
return dst, errors.New("VMess|FNV: Invalid authentication.")
}
8 years ago
return append(dst, ciphertext[4:]...), nil
}
8 years ago
// GenerateChacha20Poly1305Key generates a 32-byte key from a given 16-byte array.
func GenerateChacha20Poly1305Key(b []byte) []byte {
key := make([]byte, 32)
t := md5.Sum(b)
copy(key, t[:])
t = md5.Sum(key[:16])
copy(key[16:], t[:])
return key
}