BouncyCastle的SecureRandom在C#中是线程安全的吗? [英] Is BouncyCastle's SecureRandom in C# threadsafe?
问题描述
对于Java中的实现,答案显然是是,但是 Org.BouncyCastle如何? .Security.SecureRandom
在C#中?
The answer is apparently yes for the implementation in Java, but how about Org.BouncyCastle.Security.SecureRandom
in C#?
推荐答案
据我所知,目前还没有C#Bouncy Castle端口的官方(甚至任何)文档-我们所能做的就是查看源代码并尝试得出一些结论。这是 SecureRandom 的源代码。 。我们可以看到主要方法有 NextCounterValue
(用于生成种子)和 NextBytes
用于生成实际随机数据。 NextCounterValue
是线程安全的(使用 Interlocked.Increment
)。 NextBytes
将实现转发到 IRandomGenerator
的实例。由于您可以将 IRandomGenerator
的任何实例传递给 SecureRandom
的构造函数-我们可以得出结论,其线程安全性取决于 IRandomGenerator
已使用。
Since, as far as I know, there is no official (or even any) documentation of C# Bouncy Castle port - all we can do is look at source code and try to draw some conclusions. Here is source code of SecureRandom. We can see that the main methods there are NextCounterValue
(used to generate seeds) and NextBytes
used to generate actual random data. NextCounterValue
is thread-safe (uses Interlocked.Increment
). NextBytes
forwards implementation to instance of IRandomGenerator
. Since you can pass any instance of IRandomGenerator
to constructor of SecureRandom
- we can conclude that its thread safety depends on that of IRandomGenerator
used.
在完整的.NET Framework上, SecureRandom
使用 CryptoApiRandomGenerator 作为主生成器(用于生成种子),并且它只是.NET RNGCryptoServiceProvider
的包装,我们知道这是线程安全的。
Also when on full .NET Framework, SecureRandom
uses CryptoApiRandomGenerator as master generator (to generate seeds) and that one is just wrapper around .NET RNGCryptoServiceProvider
which as we know is thread safe.
如果仅创建 SecureRandom
而没有传递任何 IRandomGenerator
怎么办?然后它将创建 DigestRandomGenerator
的实例(代码)似乎是线程安全的(在中使用简单的
lock
What if you just create SecureRandom
without passing any IRandomGenerator
? Then it will create instance of DigestRandomGenerator
(code) which seems to be thread-safe (uses simple lock
in NextBytes
).
总而言之,我们可以说 SecureRandom
是线程安全的,如果您没有传递不是线程安全的 IRandomGenerator
实例。
All in all we can say that SecureRandom
is thread safe if you are not passing an instance of IRandomGenerator
which is not thread-safe to it.
这篇关于BouncyCastle的SecureRandom在C#中是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!