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 ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.