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