I used the System.Guid class to generate guids. I just called the Guid.NewGuid() function and used the results. For my surprise after around 25000 guid I got guids which was previously generated.
I checked the microframework source, but I didn’t saw any problem there.
So want to ask if somebody already met this problem or somebody has some kind of explanation or idea for this situation.
Guid NewGuid()
{
var rand = new Random();
var bytes = new byte[16];
for (int i = 0; i < 16; i++)
{
bytes[i] = (byte)rand.Next(255);
}
return new Guid(bytes);
}
@ sandy - According to that what Justin just wrote this might not be a very good solution.
The Windows API Implementation uses a combination of MAC Address system time time (I think at least) and counting.
By this a GUID should be world wide unique (If the computer has a network card).
I Guess the NETMF implementation is more simple.
please note the above was created for 4.2 and GHI have changed all dll references in 4.3… so i’ll leave that as an exercise for you to port to 4.3…
btw if you are using a cerb or Mountaineer family board, then you should be able to get a UNIQUE MAC per board using the above code since those chips have a unique serial number embedded
@ sandy - I don’t want to be picky, but in fact a GUID should not be random, it should be unique.
A perfect random number generator could create the same number 10 times or even more often in a row. The numbers just needs to be equally distributed if you get an unlimited number of numbers.
btw. I hate statistics :whistle: never was good in it, but this little knowledge remained somehow.
Windows default GUID algorithm (since windows 2000) generates a version 4 GUID which relies on a random number generator. Of course you would want it to be a decent PRNG.
V1 GUIDs which are sequential and based on the MAC address are considered a security risk because it exposes information about the machine the GUID was generated on and the date/time it was generated.
I just checked the NETMF implementation and it is an incomplete implementation of the V4 GUID algorithm, it is not handling the 2 significant bits of the clock sequence. Not that it would make a difference if the PRNG is useless.
So it is possible that the incorporated Random class is the guilty?
This is the current implementation from the Framework.
public static Guid NewGuid()
{
Guid newGuid = new Guid();
newGuid.m_data = new int[4];
newGuid.m_data[0] = m_rand.Next();
newGuid.m_data[1] = m_rand.Next();
newGuid.m_data[2] = m_rand.Next();
newGuid.m_data[3] = m_rand.Next();
newGuid.m_data[1] &= -1;
newGuid.m_data[1] |= 0x00000052; // the number '4'
return newGuid;
}
My only problem here is that the m_rand variable is static. This was made for this way because the Next() function to generate a new number uses the previously generated number.
So that question is if I all the time create a new instance for the m_rand variable could got better guids than the current case?