auth.go 1007 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package encoding
  2. import (
  3. "hash/fnv"
  4. "crypto/md5"
  5. "v2ray.com/core/common/crypto"
  6. "v2ray.com/core/common/serial"
  7. )
  8. func Authenticate(b []byte) uint32 {
  9. fnv1hash := fnv.New32a()
  10. fnv1hash.Write(b)
  11. return fnv1hash.Sum32()
  12. }
  13. type FnvAuthenticator struct {
  14. }
  15. func (v *FnvAuthenticator) NonceSize() int {
  16. return 0
  17. }
  18. func (v *FnvAuthenticator) Overhead() int {
  19. return 4
  20. }
  21. func (v *FnvAuthenticator) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
  22. dst = serial.Uint32ToBytes(Authenticate(plaintext), dst[:0])
  23. return append(dst, plaintext...)
  24. }
  25. func (v *FnvAuthenticator) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
  26. if serial.BytesToUint32(ciphertext[:4]) != Authenticate(ciphertext[4:]) {
  27. return dst, crypto.ErrAuthenticationFailed
  28. }
  29. return append(dst[:0], ciphertext[4:]...), nil
  30. }
  31. func GenerateChacha20Poly1305Key(b []byte) []byte {
  32. key := make([]byte, 32)
  33. t := md5.Sum(b)
  34. copy(key, t[:])
  35. t = md5.Sum(key[:16])
  36. copy(key[16:], t[:])
  37. return key
  38. }