gpt4 book ai didi

.net - 在指定范围内使用 RNGCRYPTOSERVICEPROVIDER 生成随机数

转载 作者:行者123 更新时间:2023-12-02 05:22:12 25 4
gpt4 key购买 nike

我使用以下代码生成 1000-9999 范围内的代码:

Dim byt As Byte() = New Byte(1000) {}

Dim rngCrypto As New RNGCryptoServiceProvider()
rngCrypto.GetBytes(byt)

Dim randomNumber As Integer = BitConverter.ToInt32(byt, 9999)
Label4.Text = randomNumber

显示错误:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: startIndex

我已经完成了以下代码。正确吗?

公共(public)子密码()

    Static r As Random = Nothing

If r Is Nothing Then
Dim seed() As Byte = New Byte(4) {}
Dim rng As New RNGCryptoServiceProvider
rng.GetBytes(seed)
r = New Random(BitConverter.ToInt32(seed, 0))
Label4.Text = r.Next(1000, 9999)
End If
End Sub

最佳答案

BitConverter.ToInt32 的第二个参数是字节数组的偏移量。对你来说应该是0。如果您只使用其中的 4 个字节,也没有理由获得 1000 个字节。

C# 中的工作版本:

public static int RandomUniform(int count)
{
if(count <= 0)
throw new ArgumentOutOfRangeException("count");
var rng=new RNGCryptoServiceProvider();
var bytes=new byte[8];
rng.GetBytes(bytes, 0);
return BitConverter.ToUInt64() % (uint)count;
}

Label4.Text = 1000 + RandomUniform(9000);

在 VB.net 中,这看起来类似于

Public Shared Function RandomUniform(count As Integer) As Integer
If count <= 0 Then
Throw New ArgumentOutOfRangeException("count")
End If
Dim rng = New RNGCryptoServiceProvider()
Dim bytes = New Byte(8) {}
rng.GetBytes(bytes, 0)
Return BitConverter.ToUInt64() Mod CUInt(count)
End Function

这段代码有两个弱点:

  1. 它很慢。 RNGCryptoServiceProvider.GetBytes 的每次调用开销很大。为了获得更好的性能,请使用几千字节的缓冲区,并且仅在用完时调用 GetBytes
  2. 它不是完全均匀的,但对于大多数应用来说偏差应该足够小。

    即使使用显示最大偏差的 count 值,您也需要超过 100 亿个样本来检测它,而对于 System.Random,少量样本就足够了。即偏差比 System.Random 小约 80 亿倍。

如果你不能接受任何一个弱点,你可以看看我的random number generator project它提供快速、安全和公正的数字。但这是以添加外部库而不是简单地编写几行代码为代价的。

关于.net - 在指定范围内使用 RNGCRYPTOSERVICEPROVIDER 生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13677200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com