id.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package core
  2. import (
  3. "crypto/hmac"
  4. "crypto/md5"
  5. "encoding/hex"
  6. "hash"
  7. mrand "math/rand"
  8. "time"
  9. "github.com/v2ray/v2ray-core/log"
  10. )
  11. const (
  12. IDBytesLen = 16
  13. )
  14. // The ID of en entity, in the form of an UUID.
  15. type ID struct {
  16. String string
  17. Bytes []byte
  18. hasher hash.Hash
  19. }
  20. func NewID(id string) (ID, error) {
  21. idBytes, err := UUIDToID(id)
  22. if err != nil {
  23. return ID{}, log.Error("Failed to parse id %s", id)
  24. }
  25. hasher := hmac.New(md5.New, idBytes)
  26. return ID{id, idBytes, hasher}, nil
  27. }
  28. func (v ID) TimeRangeHash(rangeSec int) []byte {
  29. nowSec := time.Now().UTC().Unix()
  30. delta := mrand.Intn(rangeSec*2) - rangeSec
  31. targetSec := nowSec + int64(delta)
  32. return v.TimeHash(targetSec)
  33. }
  34. func (v ID) TimeHash(timeSec int64) []byte {
  35. buffer := []byte{
  36. byte(timeSec >> 56),
  37. byte(timeSec >> 48),
  38. byte(timeSec >> 40),
  39. byte(timeSec >> 32),
  40. byte(timeSec >> 24),
  41. byte(timeSec >> 16),
  42. byte(timeSec >> 8),
  43. byte(timeSec),
  44. }
  45. return v.Hash(buffer)
  46. }
  47. func (v ID) Hash(data []byte) []byte {
  48. v.hasher.Write(data)
  49. hash := v.hasher.Sum(nil)
  50. v.hasher.Reset()
  51. return hash
  52. }
  53. var byteGroups = []int{8, 4, 4, 4, 12}
  54. // TODO: leverage a full functional UUID library
  55. func UUIDToID(uuid string) (v []byte, err error) {
  56. v = make([]byte, 16)
  57. text := []byte(uuid)
  58. if len(text) < 32 {
  59. err = log.Error("uuid: invalid UUID string: %s", text)
  60. return
  61. }
  62. b := v[:]
  63. for _, byteGroup := range byteGroups {
  64. if text[0] == '-' {
  65. text = text[1:]
  66. }
  67. _, err = hex.Decode(b[:byteGroup/2], text[:byteGroup])
  68. if err != nil {
  69. return
  70. }
  71. text = text[byteGroup:]
  72. b = b[byteGroup/2:]
  73. }
  74. return
  75. }