idhash.go 869 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package protocol
  2. import (
  3. "crypto/hmac"
  4. "crypto/md5"
  5. )
  6. type CounterHash interface {
  7. Hash(key []byte, counter int64) []byte
  8. }
  9. type StringHash interface {
  10. Hash(key []byte, data []byte) []byte
  11. }
  12. type TimeHash struct {
  13. baseHash StringHash
  14. }
  15. func NewTimeHash(baseHash StringHash) CounterHash {
  16. return TimeHash{
  17. baseHash: baseHash,
  18. }
  19. }
  20. func (h TimeHash) Hash(key []byte, counter int64) []byte {
  21. counterBytes := int64ToBytes(counter)
  22. return h.baseHash.Hash(key, counterBytes)
  23. }
  24. type HMACHash struct {
  25. }
  26. func (h HMACHash) Hash(key []byte, data []byte) []byte {
  27. hash := hmac.New(md5.New, key)
  28. hash.Write(data)
  29. return hash.Sum(nil)
  30. }
  31. func int64ToBytes(value int64) []byte {
  32. return []byte{
  33. byte(value >> 56),
  34. byte(value >> 48),
  35. byte(value >> 40),
  36. byte(value >> 32),
  37. byte(value >> 24),
  38. byte(value >> 16),
  39. byte(value >> 8),
  40. byte(value),
  41. }
  42. }