crypt.go 1.3 KB

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