crypt.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //go:build !confonly
  2. // +build !confonly
  3. package kcp
  4. import (
  5. "crypto/cipher"
  6. "encoding/binary"
  7. "hash/fnv"
  8. "github.com/v2fly/v2ray-core/v4/common"
  9. )
  10. // SimpleAuthenticator is a legacy AEAD used for KCP encryption.
  11. type SimpleAuthenticator struct{}
  12. // NewSimpleAuthenticator creates a new SimpleAuthenticator
  13. func NewSimpleAuthenticator() cipher.AEAD {
  14. return &SimpleAuthenticator{}
  15. }
  16. // NonceSize implements cipher.AEAD.NonceSize().
  17. func (*SimpleAuthenticator) NonceSize() int {
  18. return 0
  19. }
  20. // Overhead implements cipher.AEAD.NonceSize().
  21. func (*SimpleAuthenticator) Overhead() int {
  22. return 6
  23. }
  24. // Seal implements cipher.AEAD.Seal().
  25. func (a *SimpleAuthenticator) Seal(dst, nonce, plain, extra []byte) []byte {
  26. dst = append(dst, 0, 0, 0, 0, 0, 0) // 4 bytes for hash, and then 2 bytes for length
  27. binary.BigEndian.PutUint16(dst[4:], uint16(len(plain)))
  28. dst = append(dst, plain...)
  29. fnvHash := fnv.New32a()
  30. common.Must2(fnvHash.Write(dst[4:]))
  31. fnvHash.Sum(dst[:0])
  32. dstLen := len(dst)
  33. xtra := 4 - dstLen%4
  34. if xtra != 4 {
  35. dst = append(dst, make([]byte, xtra)...)
  36. }
  37. xorfwd(dst)
  38. if xtra != 4 {
  39. dst = dst[:dstLen]
  40. }
  41. return dst
  42. }
  43. // Open implements cipher.AEAD.Open().
  44. func (a *SimpleAuthenticator) Open(dst, nonce, cipherText, extra []byte) ([]byte, error) {
  45. dst = append(dst, cipherText...)
  46. dstLen := len(dst)
  47. xtra := 4 - dstLen%4
  48. if xtra != 4 {
  49. dst = append(dst, make([]byte, xtra)...)
  50. }
  51. xorbkd(dst)
  52. if xtra != 4 {
  53. dst = dst[:dstLen]
  54. }
  55. fnvHash := fnv.New32a()
  56. common.Must2(fnvHash.Write(dst[4:]))
  57. if binary.BigEndian.Uint32(dst[:4]) != fnvHash.Sum32() {
  58. return nil, newError("invalid auth")
  59. }
  60. length := binary.BigEndian.Uint16(dst[4:6])
  61. if len(dst)-6 != int(length) {
  62. return nil, newError("invalid auth")
  63. }
  64. return dst[6:], nil
  65. }