在.NET中创建加密安全随机GUID

我想在.NET中创建一个加密安全的GUID(v4)。

.NET的Guid.NewGuid()函数不具有加密安全性,但.NET确实提供了System.Security.Cryptography.RNGCryptoServiceProvider类。

我希望能够将随机数函数作为委托传递给Guid.NewGuid (或者甚至传递一些提供生成器接口的类)但是看起来并不像默认实现那样。

我可以通过一起使用System.GUIDSystem.Security.Cryptography.RNGCryptoServiceProvider来创建加密安全的GUID吗?

是的, Guid允许您使用字节数组创建Guid, RNGCryptoServiceProvider可以生成随机字节数组,因此您可以使用输出来提供新的Guid:

 public Guid CreateCryptographicallySecureGuid() { using (var provider = new RNGCryptoServiceProvider()) { var bytes = new byte[16]; provider.GetBytes(bytes); return new Guid(bytes); } } 

如果有人对此感兴趣,请参阅上面针对.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); } } 

https://tools.ietf.org/html/rfc4122说有一些位应该修复,以表明此GUID是版本4(随机)。 以下是更改为设置/取消设置这些位的代码。

 public Guid CreateCryptographicallySecureGuid() { using (var provider = new RNGCryptoServiceProvider()) { var bytes = new byte[16]; provider.GetBytes(bytes); bytes[8] = (byte)(bytes[8] & 0xBF | 0x80); bytes[7] = (byte)(bytes[7] & 0x4F | 0x40); return new Guid(bytes); } }