Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a cryptographically secure random GUID in .NET

I want to create a cryptographically secure GUID (v4) in .NET.

.NET's Guid.NewGuid() function is not cryptographically secure, but .NET does provide the System.Security.Cryptography.RNGCryptoServiceProvider class.

I would like to be able to pass a random number function as a delegate to Guid.NewGuid (or even pass some class that provides a generator interface) but it doesn't look as though that is possible with the default implementation.

Can I create a cryptographically secure GUID by using System.GUID and System.Security.Cryptography.RNGCryptoServiceProvider together?

like image 340
jedd.ahyoung Avatar asked May 11 '16 18:05

jedd.ahyoung


People also ask

Is a GUID cryptographically secure?

The random GUIDs you create with the Guid. NewGuid method are not known to be cryptographically secure. Thus, it's theoretically possible for a user to predict a GUID value that you generate for another user or task and use this to exploit weaknesses in your system.

How do I generate a new GUID in .NET core?

Open Visual Studio->Tools->Create GUID->Registry Format->New GUID. It will create a new GUID every time you click New GUID.

How does .NET generate GUID?

NET Core in Unix GUIDs, are generated by creating a random number of 128 bits and and doing a couple bit wise operations. In . NET Core for Windows and . NET framework it makes a remote procedure call to the Windows function UuidCreate (so it's completely up to your Windows version on how they are generated).

What is GUID NewGuid () in C#?

NET Framework using C# We can generate GUID by calling following code snippet. As you can see from this code, we use Guid. NewGuid() method to generate a new GUID in C#.


2 Answers

Yes you can, Guid allows you to create a Guid using a byte array, and RNGCryptoServiceProvider can generate a random byte array, so you can use the output to feed a new Guid:

public Guid CreateCryptographicallySecureGuid()  {     using (var provider = new RNGCryptoServiceProvider())      {         var bytes = new byte[16];         provider.GetBytes(bytes);          return new Guid(bytes);     } } 
like image 63
Gusman Avatar answered Sep 19 '22 11:09

Gusman


Read Brad M's answer below: https://stackoverflow.com/a/54132397/113535

If anyone is interested here is the above sample code adjusted for .NET Core 1.0 (DNX)

public Guid CreateCryptographicallySecureGuid() {     using (var provider = System.Security.Cryptography.RandomNumberGenerator.Create())     {         var bytes = new byte[16];         provider.GetBytes(bytes);          return new Guid(bytes);     } } 
like image 26
Kane Avatar answered Sep 21 '22 11:09

Kane