1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-27 22:36:12 -04:00
v2fly/proxy/vmess/encoding/auth.go

48 lines
999 B
Go
Raw Normal View History

2016-07-23 07:17:51 -04:00
package encoding
2016-02-27 10:41:21 -05:00
import (
"hash/fnv"
2016-12-07 11:32:40 -05:00
2016-12-07 15:43:41 -05:00
"crypto/md5"
2016-12-06 18:31:15 -05:00
"v2ray.com/core/common/crypto"
"v2ray.com/core/common/serial"
2016-02-27 10:41:21 -05:00
)
func Authenticate(b []byte) uint32 {
fnv1hash := fnv.New32a()
fnv1hash.Write(b)
return fnv1hash.Sum32()
}
2016-12-06 18:31:15 -05:00
type FnvAuthenticator struct {
}
func (v *FnvAuthenticator) NonceSize() int {
return 0
}
func (v *FnvAuthenticator) Overhead() int {
return 4
}
func (v *FnvAuthenticator) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
2016-12-07 16:52:56 -05:00
dst = serial.Uint32ToBytes(Authenticate(plaintext), dst)
2016-12-06 18:31:15 -05:00
return append(dst, plaintext...)
}
func (v *FnvAuthenticator) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
if serial.BytesToUint32(ciphertext[:4]) != Authenticate(ciphertext[4:]) {
return dst, crypto.ErrAuthenticationFailed
}
2016-12-07 16:52:56 -05:00
return append(dst, ciphertext[4:]...), nil
2016-12-06 18:31:15 -05:00
}
2016-12-07 15:43:41 -05: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
}