id.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package user
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "github.com/v2ray/v2ray-core/common/log"
  6. )
  7. const (
  8. IDBytesLen = 16
  9. )
  10. // The ID of en entity, in the form of an UUID.
  11. type ID struct {
  12. String string
  13. Bytes []byte
  14. cmdKey []byte
  15. }
  16. func NewID(id string) (ID, error) {
  17. idBytes, err := UUIDToID(id)
  18. if err != nil {
  19. return ID{}, log.Error("Failed to parse id %s", id)
  20. }
  21. md5hash := md5.New()
  22. md5hash.Write(idBytes)
  23. md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21"))
  24. cmdKey := md5.Sum(nil)
  25. return ID{
  26. String: id,
  27. Bytes: idBytes,
  28. cmdKey: cmdKey[:],
  29. }, nil
  30. }
  31. func (v ID) CmdKey() []byte {
  32. return v.cmdKey
  33. }
  34. var byteGroups = []int{8, 4, 4, 4, 12}
  35. // TODO: leverage a full functional UUID library
  36. func UUIDToID(uuid string) (v []byte, err error) {
  37. v = make([]byte, 16)
  38. text := []byte(uuid)
  39. if len(text) < 32 {
  40. err = log.Error("uuid: invalid UUID string: %s", text)
  41. return
  42. }
  43. b := v[:]
  44. for _, byteGroup := range byteGroups {
  45. if text[0] == '-' {
  46. text = text[1:]
  47. }
  48. _, err = hex.Decode(b[:byteGroup/2], text[:byteGroup])
  49. if err != nil {
  50. return
  51. }
  52. text = text[byteGroup:]
  53. b = b[byteGroup/2:]
  54. }
  55. return
  56. }