auth.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. // Authenticate authenticates a byte array using Fnv hash.
  9. func Authenticate(b []byte) uint32 {
  10. fnv1hash := fnv.New32a()
  11. fnv1hash.Write(b)
  12. return fnv1hash.Sum32()
  13. }
  14. // FnvAuthenticator is an AEAD based on Fnv hash.
  15. type FnvAuthenticator struct {
  16. }
  17. // NonceSize implements AEAD.NonceSize().
  18. func (v *FnvAuthenticator) NonceSize() int {
  19. return 0
  20. }
  21. // Overhead impelements AEAD.Overhead().
  22. func (v *FnvAuthenticator) Overhead() int {
  23. return 4
  24. }
  25. // Seal implements AEAD.Seal().
  26. func (v *FnvAuthenticator) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
  27. dst = serial.Uint32ToBytes(Authenticate(plaintext), dst)
  28. return append(dst, plaintext...)
  29. }
  30. // Open implements AEAD.Open().
  31. func (v *FnvAuthenticator) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
  32. if serial.BytesToUint32(ciphertext[:4]) != Authenticate(ciphertext[4:]) {
  33. return dst, crypto.ErrAuthenticationFailed
  34. }
  35. return append(dst, ciphertext[4:]...), nil
  36. }
  37. // GenerateChacha20Poly1305Key generates a 32-byte key from a given 16-byte array.
  38. func GenerateChacha20Poly1305Key(b []byte) []byte {
  39. key := make([]byte, 32)
  40. t := md5.Sum(b)
  41. copy(key, t[:])
  42. t = md5.Sum(key[:16])
  43. copy(key[16:], t[:])
  44. return key
  45. }