v2ray-core/proxy/vmess/encoding/auth.go

74 lines
1.7 KiB
Go
Raw Normal View History

2016-07-23 11:17:51 +00:00
package encoding
2016-02-27 15:41:21 +00:00
import (
2016-12-07 20:43:41 +00:00
"crypto/md5"
2017-01-13 22:42:39 +00:00
"hash/fnv"
2016-12-13 08:32:29 +00:00
2016-12-06 23:31:15 +00:00
"v2ray.com/core/common/serial"
2016-02-27 15:41:21 +00:00
)
2016-12-13 08:32:29 +00:00
// Authenticate authenticates a byte array using Fnv hash.
2016-02-27 15:41:21 +00:00
func Authenticate(b []byte) uint32 {
fnv1hash := fnv.New32a()
fnv1hash.Write(b)
return fnv1hash.Sum32()
}
2016-12-06 23:31:15 +00:00
2017-01-22 19:43:01 +00:00
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
}
2016-12-13 08:32:29 +00:00
// FnvAuthenticator is an AEAD based on Fnv hash.
2016-12-06 23:31:15 +00:00
type FnvAuthenticator struct {
}
2016-12-13 08:32:29 +00:00
// NonceSize implements AEAD.NonceSize().
2016-12-06 23:31:15 +00:00
func (v *FnvAuthenticator) NonceSize() int {
return 0
}
2016-12-13 08:32:29 +00:00
// Overhead impelements AEAD.Overhead().
2016-12-06 23:31:15 +00:00
func (v *FnvAuthenticator) Overhead() int {
return 4
}
2016-12-13 08:32:29 +00:00
// Seal implements AEAD.Seal().
2016-12-06 23:31:15 +00:00
func (v *FnvAuthenticator) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
2016-12-07 21:52:56 +00:00
dst = serial.Uint32ToBytes(Authenticate(plaintext), dst)
2016-12-06 23:31:15 +00:00
return append(dst, plaintext...)
}
2016-12-13 08:32:29 +00:00
// Open implements AEAD.Open().
2016-12-06 23:31:15 +00:00
func (v *FnvAuthenticator) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
if serial.BytesToUint32(ciphertext[:4]) != Authenticate(ciphertext[4:]) {
2017-04-08 23:43:25 +00:00
return dst, newError("invalid authentication")
2016-12-06 23:31:15 +00:00
}
2016-12-07 21:52:56 +00:00
return append(dst, ciphertext[4:]...), nil
2016-12-06 23:31:15 +00:00
}
2016-12-07 20:43:41 +00:00
2016-12-13 08:32:29 +00:00
// GenerateChacha20Poly1305Key generates a 32-byte key from a given 16-byte array.
2016-12-07 20:43:41 +00:00
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
}