1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-12 23:36:43 -05:00
v2fly/id.go

120 lines
2.1 KiB
Go
Raw Normal View History

2015-09-05 11:48:38 -04:00
package core
import (
2015-09-14 12:19:17 -04:00
"crypto/hmac"
2015-09-07 17:48:37 -04:00
"crypto/md5"
2015-09-06 16:10:42 -04:00
"encoding/hex"
2015-09-14 12:19:17 -04:00
mrand "math/rand"
"time"
"github.com/v2ray/v2ray-core/log"
2015-09-05 11:48:38 -04:00
)
2015-09-14 12:19:17 -04:00
const (
IDBytesLen = 16
)
2015-09-07 06:00:46 -04:00
// The ID of en entity, in the form of an UUID.
2015-09-14 12:19:17 -04:00
type ID struct {
String string
Bytes []byte
2015-09-14 15:59:44 -04:00
cmdKey []byte
2015-09-14 12:19:17 -04:00
}
func NewID(id string) (ID, error) {
idBytes, err := UUIDToID(id)
if err != nil {
return ID{}, log.Error("Failed to parse id %s", id)
}
2015-09-15 18:06:22 -04:00
md5hash := md5.New()
2015-09-14 15:59:44 -04:00
md5hash.Write(idBytes)
md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21"))
cmdKey := md5.Sum(nil)
return ID{id, idBytes, cmdKey[:]}, nil
2015-09-14 12:19:17 -04:00
}
2015-09-14 19:32:55 -04:00
func (v ID) TimeRangeHash(rangeSec int) ([]byte, int64) {
2015-09-14 12:19:17 -04:00
nowSec := time.Now().UTC().Unix()
delta := mrand.Intn(rangeSec*2) - rangeSec
targetSec := nowSec + int64(delta)
2015-09-14 19:32:55 -04:00
return v.TimeHash(targetSec), targetSec
2015-09-14 12:19:17 -04:00
}
func (v ID) TimeHash(timeSec int64) []byte {
buffer := []byte{
byte(timeSec >> 56),
byte(timeSec >> 48),
byte(timeSec >> 40),
byte(timeSec >> 32),
byte(timeSec >> 24),
byte(timeSec >> 16),
byte(timeSec >> 8),
byte(timeSec),
}
return v.Hash(buffer)
}
func (v ID) Hash(data []byte) []byte {
2015-09-15 18:06:22 -04:00
hasher := hmac.New(md5.New, v.Bytes)
2015-09-14 15:59:44 -04:00
hasher.Write(data)
return hasher.Sum(nil)
}
func (v ID) CmdKey() []byte {
return v.cmdKey
2015-09-07 17:48:19 -04:00
}
2015-09-14 19:32:55 -04:00
func TimestampHash(timeSec int64) []byte {
2015-09-15 18:06:22 -04:00
md5hash := md5.New()
buffer := []byte{
2015-09-14 19:32:55 -04:00
byte(timeSec >> 56),
byte(timeSec >> 48),
byte(timeSec >> 40),
byte(timeSec >> 32),
byte(timeSec >> 24),
byte(timeSec >> 16),
byte(timeSec >> 8),
byte(timeSec),
}
md5hash.Write(buffer)
2015-09-15 18:06:22 -04:00
md5hash.Write(buffer)
md5hash.Write(buffer)
md5hash.Write(buffer)
2015-09-14 19:32:55 -04:00
return md5hash.Sum(nil)
}
2015-09-05 11:48:38 -04:00
var byteGroups = []int{8, 4, 4, 4, 12}
// TODO: leverage a full functional UUID library
2015-09-14 12:19:17 -04:00
func UUIDToID(uuid string) (v []byte, err error) {
v = make([]byte, 16)
2015-09-06 16:10:42 -04:00
text := []byte(uuid)
if len(text) < 32 {
err = log.Error("uuid: invalid UUID string: %s", text)
2015-09-05 11:48:38 -04:00
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
}