auth.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package encoding
  2. import (
  3. "crypto/md5"
  4. "encoding/binary"
  5. "hash/fnv"
  6. "github.com/xtls/xray-core/common"
  7. "github.com/xtls/xray-core/common/crypto"
  8. "golang.org/x/crypto/sha3"
  9. )
  10. // Authenticate authenticates a byte array using Fnv hash.
  11. func Authenticate(b []byte) uint32 {
  12. fnv1hash := fnv.New32a()
  13. common.Must2(fnv1hash.Write(b))
  14. return fnv1hash.Sum32()
  15. }
  16. // [DEPRECATED 2023-06]
  17. type NoOpAuthenticator struct{}
  18. func (NoOpAuthenticator) NonceSize() int {
  19. return 0
  20. }
  21. func (NoOpAuthenticator) Overhead() int {
  22. return 0
  23. }
  24. // Seal implements AEAD.Seal().
  25. func (NoOpAuthenticator) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
  26. return append(dst[:0], plaintext...)
  27. }
  28. // Open implements AEAD.Open().
  29. func (NoOpAuthenticator) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
  30. return append(dst[:0], ciphertext...), nil
  31. }
  32. // GenerateChacha20Poly1305Key generates a 32-byte key from a given 16-byte array.
  33. func GenerateChacha20Poly1305Key(b []byte) []byte {
  34. key := make([]byte, 32)
  35. t := md5.Sum(b)
  36. copy(key, t[:])
  37. t = md5.Sum(key[:16])
  38. copy(key[16:], t[:])
  39. return key
  40. }
  41. type ShakeSizeParser struct {
  42. shake sha3.ShakeHash
  43. buffer [2]byte
  44. }
  45. func NewShakeSizeParser(nonce []byte) *ShakeSizeParser {
  46. shake := sha3.NewShake128()
  47. common.Must2(shake.Write(nonce))
  48. return &ShakeSizeParser{
  49. shake: shake,
  50. }
  51. }
  52. func (*ShakeSizeParser) SizeBytes() int32 {
  53. return 2
  54. }
  55. func (s *ShakeSizeParser) next() uint16 {
  56. common.Must2(s.shake.Read(s.buffer[:]))
  57. return binary.BigEndian.Uint16(s.buffer[:])
  58. }
  59. func (s *ShakeSizeParser) Decode(b []byte) (uint16, error) {
  60. mask := s.next()
  61. size := binary.BigEndian.Uint16(b)
  62. return mask ^ size, nil
  63. }
  64. func (s *ShakeSizeParser) Encode(size uint16, b []byte) []byte {
  65. mask := s.next()
  66. binary.BigEndian.PutUint16(b, mask^size)
  67. return b[:2]
  68. }
  69. func (s *ShakeSizeParser) NextPaddingLen() uint16 {
  70. return s.next() % 64
  71. }
  72. func (s *ShakeSizeParser) MaxPaddingLen() uint16 {
  73. return 64
  74. }
  75. type AEADSizeParser struct {
  76. crypto.AEADChunkSizeParser
  77. }
  78. func NewAEADSizeParser(auth *crypto.AEADAuthenticator) *AEADSizeParser {
  79. return &AEADSizeParser{crypto.AEADChunkSizeParser{Auth: auth}}
  80. }