C# 随机 BigInt 生成器

标签 c# biginteger dsa

我即将实现 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/

相关文章:

dsa - 如何将 DSA 私钥转换为 byte[] ?

c# - 全网数据同步

java - RSA key 生成的 BigInteger 实现

c# - 如何更改c#中窗口窗体的原点即左上角和openGL C即中心?

java - 在 Java 中总结两个巨大的长

c# - 将大数字分配给 BigInteger 时出错

android - 适用于 Android 的 Keytool 公钥/私钥对

encryption - DSA key 大小

c# - 如何识别非人类用户?

c# - Ravendb mapreduce 按多个字段分组