gpt4 book ai didi

C# 随机 BigInt 生成器

转载 作者:可可西里 更新时间:2023-11-01 08:23:05 64 4
gpt4 key购买 nike

我即将实现 DSA algorithm ,但有一个问题:

choose "p", a prime number with L bits, where 512 <= L <= 1024 and L is a multiple of 64

如何实现该数字的随机生成器? Int64 的长度“只有”63 位。

最佳答案

您可以使用以下代码生成具有 n 位的随机数:

var rng = new RNGCryptoServiceProvider();
byte[] bytes = new byte[n / 8];
rng.GetBytes(bytes);

BigInteger p = new BigInteger(bytes);

当然,结果是随机的,不一定是素数。

BigInteger class在 .NET 4.0 Framework 中引入。


为了生成大质数,Wikipedia says :

For the large primes used in cryptography, it is usual to use a modified form of sieving: a randomly-chosen range of odd numbers of the desired size is sieved against a number of relatively small odd primes (typically all primes less than 65,000). The remaining candidate primes are tested in random order with a standard primality test such as the Miller-Rabin primality test for probable primes.

所以你可以这样做:

var p = Enumerable.Range(0, numberOfCandidates)
.Select(i => RandomOddNumber(bits))
.Where(x => !primesLessThan65000.Contains(x))
.Where(x => PrimalityTest(x))
.FirstOrDefault();

关于C# 随机 BigInt 生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2965707/

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