mirror of
https://github.com/v2ray/v2ray-core.git
synced 2026-11-16 14:53:12 +00:00
Time based user hash
This commit is contained in:
1 parent
89f9332abd
commit
097915bf7e
11 files changed
+142
-68
No files matched your search
@@ -1,27 +1,68 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"hash"
|
||||
mrand "math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/v2ray/v2ray-core/log"
|
||||
)
|
||||
|
||||
// The ID of en entity, in the form of an UUID.
|
||||
type ID [16]byte
|
||||
const (
|
||||
IDBytesLen = 16
|
||||
)
|
||||
|
||||
// Hash generates a MD5 hash based on current ID and a suffix string.
|
||||
func (v ID) Hash(suffix []byte) []byte {
|
||||
md5 := md5.New()
|
||||
md5.Write(v[:])
|
||||
md5.Write(suffix)
|
||||
return md5.Sum(nil)
|
||||
// The ID of en entity, in the form of an UUID.
|
||||
type ID struct {
|
||||
String string
|
||||
Bytes []byte
|
||||
hasher hash.Hash
|
||||
}
|
||||
|
||||
func NewID(id string) (ID, error) {
|
||||
idBytes, err := UUIDToID(id)
|
||||
if err != nil {
|
||||
return ID{}, log.Error("Failed to parse id %s", id)
|
||||
}
|
||||
hasher := hmac.New(md5.New, idBytes)
|
||||
return ID{id, idBytes, hasher}, nil
|
||||
}
|
||||
|
||||
func (v ID) TimeRangeHash(rangeSec int) []byte {
|
||||
nowSec := time.Now().UTC().Unix()
|
||||
delta := mrand.Intn(rangeSec*2) - rangeSec
|
||||
|
||||
targetSec := nowSec + int64(delta)
|
||||
return v.TimeHash(targetSec)
|
||||
}
|
||||
|
||||
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 {
|
||||
return v.hasher.Sum(data)
|
||||
}
|
||||
|
||||
var byteGroups = []int{8, 4, 4, 4, 12}
|
||||
|
||||
// TODO: leverage a full functional UUID library
|
||||
func UUIDToID(uuid string) (v ID, err error) {
|
||||
func UUIDToID(uuid string) (v []byte, err error) {
|
||||
v = make([]byte, 16)
|
||||
|
||||
text := []byte(uuid)
|
||||
if len(text) < 32 {
|
||||
err = log.Error("uuid: invalid UUID string: %s", text)
|
||||
|
||||
Reference in new issue
Block a user