如何在 C# 中生成加密安全的伪随机数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1668353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:50:40  来源:igfitidea点击:

How can I generate a cryptographically secure pseudorandom number in C#?

c#cryptography

提问by Alon Gubkin

Is there any fast implementation of cryptographically secure pseudorandom number generator(CSPRNG) for C# 3.0 (.NET Framework 3.5), for authentication tokens?

C# 3.0 (.NET Framework 3.5)的加密安全伪随机数生成器(CSPRNG)是否有任何快速实现,用于身份验证令牌?

采纳答案by John Gietzen

using System.Security.Cryptography;
...
using(RandomNumberGenerator rng = new RNGCryptoServiceProvider())
{
    byte[] tokenData = new byte[32];
    rng.GetBytes(tokenData);

    string token = Convert.ToBase64String(tokenData);
}

回答by stuartd

回答by Guffa

That depends on what you mean by fast...

这取决于你所说的快速是什么意思......

There is no really fast secure random generator. If you want fast, you should use the regular Random class. If you want secure you should use the random generator in the Cryptography namespace, but that is significantly slower. You simply can't have both.

没有真正快速安全的随机生成器。如果你想快速,你应该使用常规的 Random 类。如果你想要安全,你应该在 Cryptography 命名空间中使用随机生成器,但那会慢得多。你不能两者兼得。