From fea09a6b74b7cd24e3c808b74ee91d2381f3f234 Mon Sep 17 00:00:00 2001 From: MichalPetryka <35800402+MichalPetryka@users.noreply.github.com> Date: Sun, 14 Apr 2019 14:16:19 +0200 Subject: [PATCH] Improve SceneID generation via RNGCryptoServiceProvider (#812) * Improve SceneID generation * Update NetworkIdentity.cs --- Assets/Mirror/Runtime/NetworkIdentity.cs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/Assets/Mirror/Runtime/NetworkIdentity.cs b/Assets/Mirror/Runtime/NetworkIdentity.cs index 6735916f9..e470f4cf6 100644 --- a/Assets/Mirror/Runtime/NetworkIdentity.cs +++ b/Assets/Mirror/Runtime/NetworkIdentity.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Linq; +using System.Security.Cryptography; using UnityEngine; using UnityEngine.Serialization; #if UNITY_EDITOR @@ -217,6 +218,17 @@ bool ThisIsASceneObjectWithPrefabParent(out GameObject prefab) return true; } + static uint GetRandomUInt() + { + // use Crypto RNG to avoid having time based duplicates + using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) + { + byte[] bytes = new byte[4]; + rng.GetBytes(bytes); + return BitConverter.ToUInt32(bytes, 0); + } + } + // persistent sceneId assignment // (because scene objects have no persistent unique ID in Unity) // @@ -295,9 +307,7 @@ void AssignSceneID() Undo.RecordObject(this, "Generated SceneId"); // generate random sceneId part (0x00000000FFFFFFFF) - // -> exclude '0' because that's for unassigned sceneIDs - // TODO use 0,uint.max later. Random.Range only has int version. - uint randomId = (uint)UnityEngine.Random.Range(1, int.MaxValue); + uint randomId = GetRandomUInt(); // only assign if not a duplicate of an existing scene id // (small chance, but possible)