id.go 2.1 KB

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