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?
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.
Open Visual Studio->Tools->Create GUID->Registry Format->New GUID. It will create a new GUID every time you click New 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).
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#.
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); } }
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With