From 82621cd1bf9bf9976f787b69e06677ce0daeb21e Mon Sep 17 00:00:00 2001 From: wwqgtxx Date: Sun, 26 Apr 2026 09:31:51 +0800 Subject: [PATCH] chore: always safe UUID generation --- common/utils/uuid.go | 25 ++----------------------- common/utils/uuid_test.go | 11 ----------- 2 files changed, 2 insertions(+), 34 deletions(-) diff --git a/common/utils/uuid.go b/common/utils/uuid.go index 1937cd18a..c112ef216 100644 --- a/common/utils/uuid.go +++ b/common/utils/uuid.go @@ -2,33 +2,12 @@ package utils import ( "crypto/md5" + "crypto/rand" "crypto/sha1" - "unsafe" "github.com/gofrs/uuid/v5" - "github.com/metacubex/randv2" ) -func UnsafeRandRead(p []byte) { - for len(p) > 0 { - v := randv2.Uint64() - if v == 0 { - continue - } - i := copy(p, (*[8]byte)(unsafe.Pointer(&v))[:]) - p = p[i:] - } -} - -type unsafeRandReader struct{} - -func (r *unsafeRandReader) Read(p []byte) (n int, err error) { - UnsafeRandRead(p) - return len(p), nil -} - -var UnsafeRandReader = (*unsafeRandReader)(nil) - // NewUUIDV3 returns a UUID based on the MD5 hash of the namespace UUID and name. func NewUUIDV3(ns uuid.UUID, name string) (u uuid.UUID) { h := md5.New() @@ -45,7 +24,7 @@ func NewUUIDV3(ns uuid.UUID, name string) (u uuid.UUID) { // // Version 4 UUIDs contain 122 bits of random data. func NewUUIDV4() (u uuid.UUID) { - UnsafeRandRead(u[:]) + rand.Read(u[:]) u.SetVersion(uuid.V4) u.SetVariant(uuid.VariantRFC9562) return u diff --git a/common/utils/uuid_test.go b/common/utils/uuid_test.go index 5462af7b8..34ee0e3e4 100644 --- a/common/utils/uuid_test.go +++ b/common/utils/uuid_test.go @@ -1,23 +1,12 @@ package utils import ( - "bytes" "reflect" "testing" "github.com/gofrs/uuid/v5" ) -func TestUnsafeRandRead(t *testing.T) { - for i := 1; i < 100; i++ { - data := make([]byte, i) - UnsafeRandRead(data) - if bytes.Equal(data, make([]byte, i)) { - t.Fatal("UnsafeRandRead should not return all zero bytes") - } - } -} - func TestUUIDMap(t *testing.T) { type args struct { str string