-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cryptographic GUID.linq
89 lines (74 loc) · 1.85 KB
/
Cryptographic GUID.linq
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<Query Kind="Program">
<Namespace>System.Security.Cryptography</Namespace>
</Query>
void Main()
{
Guid g = CryptoGuid.New();
g.Dump();
/*
byte b1 = 0;
byte b2 = 0;
string yourByteString;
yourByteString = Convert.ToString(b1, 2).PadLeft(8, '0');
Console.WriteLine(yourByteString);
Console.WriteLine("Version");
b1 = (byte)(b2 & 0x0F | 0x40);
yourByteString = Convert.ToString(b1, 2).PadLeft(8, '0');
Console.WriteLine(yourByteString);
b2 = (byte)(b2 & 0x4F | 0x40);
yourByteString = Convert.ToString(b2, 2).PadLeft(8, '0');
Console.WriteLine(yourByteString);
Console.WriteLine("Variant");
b1 = (byte)(b2 & 0x3F | 0x80);
yourByteString = Convert.ToString(b1, 2).PadLeft(8, '0');
Console.WriteLine(yourByteString);
b2 = (byte)(b2 & 0xBF | 0x80);
yourByteString = Convert.ToString(b2, 2).PadLeft(8, '0');
Console.WriteLine(yourByteString);
*/
}
// https://tools.ietf.org/html/rfc4122#section-4.1.1
public class CryptoGuid
{
public static Guid New()
{
Guid rc;
byte[] b = new byte[16];
RandomNumberGenerator.Fill(b);
// clear first 4 bits then set set first 4 bit to 0100
if(BitConverter.IsLittleEndian)
{
b[7] = (byte)(b[7] & 0x0F | 0x40);
}
else
{
b[6] = (byte)(b[6] & 0x0F | 0x40);
}
// clear first 2 bits then set first to bits to 10**
b[8] = (byte)(b[8] & 0x3F | 0x80);
rc = new Guid(b);
return rc;
}
}
// https://tools.ietf.org/html/rfc4122#section-4.1.1
class CryptographicGuidGenerator
{
public static Guid New()
{
byte[] b = new byte[16];
RandomNumberGenerator.Fill(b);
// clear first 4 bits then set set first 4 bit to 0100
if (BitConverter.IsLittleEndian)
{
b[7] = (byte)(b[7] & 0x0F | 0x40);
}
else
{
b[6] = (byte)(b[6] & 0x0F | 0x40);
}
// clear first 2 bits then set first to bits to 10**
b[8] = (byte)(b[8] & 0x3F | 0x80);
Guid rc = new Guid(b);
return rc;
}
}