Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate UUID version 4 using c#

My requirement is to generate version 4 UUID from C# code for google API session token and i am not sure Guid.NewGuid() method, Which version of GUID does it return. Like version

Read google and blog but not get sure answer Does Guid.NewGuid() produce UUID version 4 according to RFC4122?

Thanks in advance

like image 441
Mansinh Avatar asked Apr 24 '19 06:04

Mansinh


People also ask

How is UUID v4 generated?

This version of UUID is generated randomly. Although the random UUID uses random bytes, four bits are used to indicate version 4, while two to three bits are used to indicate the variant. These can be created using a random or pseudo-random number generator.

What is a version 4 UUID?

A version 4 UUID is a randomly generated 128-bit identifier. As in other UUIDs, 4 bits are used to indicate version 4, and 2 bits are used to indicate the variant. Thus, 6 bits are constant, leaving 122 bits for the randomly generated part, for a total of 2122 (5.3×1036, 5.3 undecillion) possible values.

Is UUID v4 time based?

UUID v4 differs from other versions in that it is not based on any easily reproducible data (MAC/timestamp for v1, name/namespace for v3 and v5). Instead, v4 generates unique identifiers based on random numbers (pseudo-random).


1 Answers

GUIDs are V4... every single GUID you generate will look like this

18acac20-991e-437e-9529-a441452f6b7e
d6d68639-64c2-452e-95b7-16cf6dbf5301
b0943b6d-4779-4771-92bf-cc2d634fb671
218b5620-d30d-46d9-9c88-38a4ac64266e
de03042c-792f-4689-80ca-26287ceb2129
1175bb5d-d35e-4a46-aaac-0825c749dc3a
42864583-c0f6-4e44-8710-39c9a9146d43
223ca924-4b77-4931-bb94-c1d371894683
2c4495ab-19e4-4aeb-b647-10db8625791c
f5894345-cbe3-4fc7-92c3-d6d863f70411
              ^    ^
              1    2

The digit at position 1 above is always 4 and the digit at position 2 is always one of 8, 9, A or B.

You can confirm this by

var cts = new CancellationTokenSource();

var parallelOptions = new ParallelOptions() { MaxDegreeOfParallelism = 8, CancellationToken = cts.Token };
Parallel.For(0, int.MaxValue, parallelOptions, (i) =>
{
    var guid = Guid.NewGuid().ToString();
    var four = guid.ElementAt(14);
    var ab89 = guid.ElementAt(19);

    if (four != '4') cts.Cancel();
    if (ab89 != 'a' && ab89 != 'b' && ab89 != '8' && ab89 != '9') cts.Cancel();

    if ((i % 100000) == 0 && i < (int.MaxValue / 8))
    {
        Console.WriteLine($"{i * 8:n}"); // roughly   
    }
});

That will run through 4billion'ish attempts in a reasonable amount of time if you have doubts

like image 80
Aydin Avatar answered Sep 19 '22 18:09

Aydin