ota.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package shadowsocks
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha1"
  5. "github.com/v2ray/v2ray-core/common/serial"
  6. )
  7. const (
  8. AuthSize = 10
  9. )
  10. type KeyGenerator func() []byte
  11. type Authenticator struct {
  12. key KeyGenerator
  13. }
  14. func NewAuthenticator(keygen KeyGenerator) *Authenticator {
  15. return &Authenticator{
  16. key: keygen,
  17. }
  18. }
  19. func (this *Authenticator) AuthSize() int {
  20. return AuthSize
  21. }
  22. func (this *Authenticator) Authenticate(auth []byte, data []byte) []byte {
  23. hasher := hmac.New(sha1.New, this.key())
  24. hasher.Write(data)
  25. res := hasher.Sum(nil)
  26. return append(auth, res[:AuthSize]...)
  27. }
  28. func HeaderKeyGenerator(key []byte, iv []byte) func() []byte {
  29. return func() []byte {
  30. newKey := make([]byte, 0, len(key)+len(iv))
  31. newKey = append(newKey, key...)
  32. newKey = append(newKey, iv...)
  33. return newKey
  34. }
  35. }
  36. func ChunkKeyGenerator(iv []byte) func() []byte {
  37. chunkId := 0
  38. return func() []byte {
  39. newKey := make([]byte, 0, len(iv)+4)
  40. newKey = append(newKey, iv...)
  41. newKey = append(newKey, serial.IntLiteral(chunkId).Bytes()...)
  42. chunkId++
  43. return newKey
  44. }
  45. }