O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generate a Secure Random GUID

Problem

You want to create a cryptographically secure, random globally unique identifier (GUID).

Solution

Use the RNGCryptoServiceProvider class to create 16 random bytes, and then use these to create a new GUID by passing them to the Guid constructor.

Discussion

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. To prevent this possibility, you can create a cryptographically secure GUID using the RNGCryptoServiceProvider class. Here’s the code you need:

Public Module RandomGuidGenerator Public Sub Main() ' A ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required