本文介绍了BouncyCastle的SecureRandom在C#中是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于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端口的官方(甚至任何)文档-我们所能做的就是查看源代码并尝试得出一些结论。这是的源代码。 。我们可以看到主要方法有 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 使用)似乎是线程安全的(在中使用简单的 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#中是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:41