auth.go 821 B

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