在.NET中创建加密安全的随机GUID [英] Create a cryptographically secure random GUID in .NET
问题描述
我想在.NET中创建一个加密安全的GUID(v4)。
I want to create a cryptographically secure GUID (v4) in .NET.
.NET的 Guid.NewGuid()
函数不是加密安全的,但是.NET确实提供了 System.Security.Cryptography.RNGCryptoServiceProvider
类。
.NET's Guid.NewGuid()
function is not cryptographically secure, but .NET does provide the System.Security.Cryptography.RNGCryptoServiceProvider
class.
我希望能够将随机数函数作为委托传递给 Guid.NewGuid
(甚至传递一些提供生成器接口的类),但它不会
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.
我可以使用 System.GUID $ c $创建一个加密安全的GUID吗? c>和
System.Security.Cryptography.RNGCryptoServiceProvider
在一起?
推荐答案
是的,您可以,向导允许您使用字节数组创建Guid ,和 RNGCryptoServicePro vider 可以生成一个随机字节数组,因此您可以使用输出来提供新的Guid:
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);
}
}
这篇关于在.NET中创建加密安全的随机GUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!