简体   繁体   中英

Is BouncyCastle's SecureRandom in C# threadsafe?

对于Java中的实现,答案显然是肯定的,但C#中的Org.BouncyCastle.Security.SecureRandom怎么样?

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM