Advertisement
TizzyT

LargePrimeGen - TizzyT

Feb 16th, 2014
1,214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.82 KB | None | 0 0
  1. ''' Large Prime Generator '''
  2.     Public Function PrimeGen(ByVal length As Integer, ByRef Rand As Random, _
  3.                              Optional ByVal iteration As Integer = 0) As BigInteger
  4.         If length < 2 Then length = 2
  5.         If iteration = 0 Then iteration = Math.Sqrt(length)
  6.         Dim temp, r, y, a(iteration - 1) As BigInteger
  7.         PrimeGen = RandBigInt(length, Rand)
  8.         While True
  9.             If PrimeGen.IsEven Then PrimeGen -= 1
  10.             If PrimeGen Mod 5 = 0 Then PrimeGen -= 2
  11.             If PrimeGen <= 3 Then Return Rand.Next(2, 4)
  12.             For i = 0 To a.Length - 1
  13.                 While a(i) <= 2 Or a(i) >= PrimeGen - 2 : a(i) = RandBigInt(length, Rand) : End While
  14.             Next
  15.             r = New BigInteger((PrimeGen - 1).ToByteArray())
  16.             While r Mod 2 = 0 : r = r / 2 : End While
  17.             For i = 0 To iteration - 1
  18.                 temp = r
  19.                 y = BigInteger.ModPow(a(i), r, PrimeGen)
  20.                 While temp <> PrimeGen - 1 AndAlso y <> 1 AndAlso y <> PrimeGen - 1
  21.                     y = BigInteger.ModPow(y, 2, PrimeGen)
  22.                     temp = BigInteger.Multiply(temp, 2)
  23.                 End While
  24.                 If y <> PrimeGen - 1 AndAlso BigInteger.ModPow(temp, 1, 2) = 0 Then : Exit For
  25.                 ElseIf i = iteration - 1 Then : Return PrimeGen : End If
  26.             Next
  27.             PrimeGen -= 2
  28.         End While
  29.     End Function
  30.  
  31.     Private Function RandBigInt(ByVal BitLength As BigInteger, ByRef Rnd As Random) As BigInteger
  32.         Dim Rmdr, numParts(BigInteger.DivRem(BitLength, 8, Rmdr)) As Byte
  33.         For i = 0 To numParts.Length - 2 : numParts(i) = Rnd.Next(0, 256) : Next
  34.         numParts(numParts.Length - 1) = If(Rmdr = 0, 0, Rnd.Next(0, 2 ^ Rmdr - 1))
  35.         RandBigInt = New BigInteger(numParts)
  36.     End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement