auth.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package encoding
  2. import (
  3. "crypto/md5"
  4. "hash/fnv"
  5. "golang.org/x/crypto/sha3"
  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, newError("invalid authentication")
  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. }
  46. type ShakeSizeParser struct {
  47. shake sha3.ShakeHash
  48. buffer [2]byte
  49. }
  50. func NewShakeSizeParser(nonce []byte) *ShakeSizeParser {
  51. shake := sha3.NewShake128()
  52. shake.Write(nonce)
  53. return &ShakeSizeParser{
  54. shake: shake,
  55. }
  56. }
  57. func (s *ShakeSizeParser) SizeBytes() int {
  58. return 2
  59. }
  60. func (s *ShakeSizeParser) next() uint16 {
  61. s.shake.Read(s.buffer[:])
  62. return serial.BytesToUint16(s.buffer[:])
  63. }
  64. func (s *ShakeSizeParser) Decode(b []byte) (uint16, error) {
  65. mask := s.next()
  66. size := serial.BytesToUint16(b)
  67. return mask ^ size, nil
  68. }
  69. func (s *ShakeSizeParser) Encode(size uint16, b []byte) []byte {
  70. mask := s.next()
  71. return serial.Uint16ToBytes(mask^size, b[:0])
  72. }