id.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 [IDBytesLen]byte
  14. cmdKey [IDBytesLen]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 [IDBytesLen]byte, err error) {
  37. text := []byte(uuid)
  38. if len(text) < 32 {
  39. err = log.Error("uuid: invalid UUID string: %s", text)
  40. return
  41. }
  42. b := v[:]
  43. for _, byteGroup := range byteGroups {
  44. if text[0] == '-' {
  45. text = text[1:]
  46. }
  47. _, err = hex.Decode(b[:byteGroup/2], text[:byteGroup])
  48. if err != nil {
  49. return
  50. }
  51. text = text[byteGroup:]
  52. b = b[byteGroup/2:]
  53. }
  54. return
  55. }