crypt.go 1.6 KB

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