forked from v2ray/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
id.go
78 lines (61 loc) · 1.24 KB
/
id.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package vmess
import (
"crypto/md5"
"encoding/hex"
"errors"
"github.com/v2ray/v2ray-core/common/log"
)
const (
IDBytesLen = 16
)
var (
InvalidID = errors.New("Invalid ID.")
)
// The ID of en entity, in the form of an UUID.
type ID struct {
String string
Bytes [IDBytesLen]byte
cmdKey [IDBytesLen]byte
}
func NewID(id string) (*ID, error) {
idBytes, err := UUIDToID(id)
if err != nil {
log.Error("Failed to parse id %s", id)
return &ID{}, InvalidID
}
md5hash := md5.New()
md5hash.Write(idBytes[:])
md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21"))
cmdKey := md5.Sum(nil)
return &ID{
String: id,
Bytes: idBytes,
cmdKey: cmdKey,
}, nil
}
func (v ID) CmdKey() []byte {
return v.cmdKey[:]
}
var byteGroups = []int{8, 4, 4, 4, 12}
// TODO: leverage a full functional UUID library
func UUIDToID(uuid string) (v [IDBytesLen]byte, err error) {
text := []byte(uuid)
if len(text) < 32 {
log.Error("uuid: invalid UUID string: %s", text)
err = InvalidID
return
}
b := v[:]
for _, byteGroup := range byteGroups {
if text[0] == '-' {
text = text[1:]
}
_, err = hex.Decode(b[:byteGroup/2], text[:byteGroup])
if err != nil {
return
}
text = text[byteGroup:]
b = b[byteGroup/2:]
}
return
}