internal bool FindTwoFactorsWithFermat( Integer Product, Integer P, Integer Q, ulong MinimumX ) { ECTime StartTime = new ECTime(); StartTime.SetToNow(); Integer TestSqrt = new Integer(); Integer TestSquared = new Integer(); Integer SqrRoot = new Integer(); TestSquared.Copy( Product ); IntMath.Multiply( TestSquared, Product ); IntMath.SquareRoot( TestSquared, SqrRoot ); TestSqrt.Copy( SqrRoot ); IntMath.DoSquare( TestSqrt ); // IntMath.Multiply( TestSqrt, SqrRoot ); if( !TestSqrt.IsEqual( TestSquared )) throw( new Exception( "The square test was bad." )); // Some primes: // 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, // 101, 103, 107 P.SetToZero(); Q.SetToZero(); Integer TestX = new Integer(); SetupQuadResArray( Product ); ulong BaseTo37 = QuadResBigBase * 29UL * 31UL * 37UL; // ulong BaseTo31 = QuadResBigBase * 29UL * 31UL; ulong ProdModTo37 = IntMath.GetMod64( Product, BaseTo37 ); // ulong ProdModTo31 = IntMath.GetMod64( Product, BaseTo31 ); for( ulong BaseCount = 0; BaseCount < (29 * 31 * 37); BaseCount++ ) { if( (BaseCount & 0xF) == 0 ) Worker.ReportProgress( 0, "Find with Fermat BaseCount: " + BaseCount.ToString() ); if( Worker.CancellationPending ) return false; ulong Base = (BaseCount + 1) * QuadResBigBase; // BaseCount times 223,092,870. if( Base < MinimumX ) continue; Base = BaseCount * QuadResBigBase; // BaseCount times 223,092,870. for( uint Count = 0; Count < QuadResArrayLast; Count++ ) { // The maximum CountPart can be is just under half the size of // the Product. (Like if Y - X was equal to 1, and Y + X was // equal to the Product.) If it got anywhere near that big it // would be inefficient to try and find it this way. ulong CountPart = Base + QuadResArray[Count]; ulong Test = ProdModTo37 + (CountPart * CountPart); // ulong Test = ProdModTo31 + (CountPart * CountPart); Test = Test % BaseTo37; // Test = Test % BaseTo31; if( !IntegerMath.IsQuadResidue29( Test )) continue; if( !IntegerMath.IsQuadResidue31( Test )) continue; if( !IntegerMath.IsQuadResidue37( Test )) continue; ulong TestBytes = (CountPart & 0xFFFFF); TestBytes *= (CountPart & 0xFFFFF); ulong ProdBytes = Product.GetD( 1 ); ProdBytes <<= 8; ProdBytes |= Product.GetD( 0 ); uint FirstBytes = (uint)(TestBytes + ProdBytes); if( !IntegerMath.FirstBytesAreQuadRes( FirstBytes )) { // Worker.ReportProgress( 0, "First bytes aren't quad res." ); continue; } TestX.SetFromULong( CountPart ); IntMath.MultiplyULong( TestX, CountPart ); TestX.Add( Product ); // uint Mod37 = (uint)IntMath.GetMod32( TestX, 37 ); // if( !IntegerMath.IsQuadResidue37( Mod37 )) // continue; // Do more of these tests with 41, 43, 47... // if( !IntegerMath.IsQuadResidue41( Mod37 )) // continue; // Avoid doing this square root at all costs. if( IntMath.SquareRoot( TestX, SqrRoot )) { Worker.ReportProgress( 0, " " ); if( (CountPart & 1) == 0 ) Worker.ReportProgress( 0, "CountPart was even." ); else Worker.ReportProgress( 0, "CountPart was odd." ); // Found an exact square root. // P + (CountPart * CountPart) = Y*Y // P = (Y + CountPart)Y - CountPart) P.Copy( SqrRoot ); Integer ForSub = new Integer(); ForSub.SetFromULong( CountPart ); IntMath.Subtract( P, ForSub ); // Make Q the bigger one and put them in order. Q.Copy( SqrRoot ); Q.AddULong( CountPart ); if( P.IsOne() || Q.IsOne()) { // This happens when testing with small primes. Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "Went all the way to 1 in FindTwoFactorsWithFermat()." ); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, " " ); P.SetToZero(); // It has no factors. Q.SetToZero(); return true; // Tested everything, so it's a prime. } Worker.ReportProgress( 0, "Found P: " + IntMath.ToString10( P ) ); Worker.ReportProgress( 0, "Found Q: " + IntMath.ToString10( Q ) ); Worker.ReportProgress( 0, "Seconds: " + StartTime.GetSecondsToNow().ToString( "N1" )); Worker.ReportProgress( 0, " " ); throw( new Exception( "Testing this." )); // return true; // With P and Q. } // else // Worker.ReportProgress( 0, "It was not an exact square root." ); } } // P and Q would still be zero if it never found them. return false; }
internal void MakeRSAKeys() { int ShowBits = (PrimeIndex + 1) * 32; // int TestLoops = 0; Worker.ReportProgress( 0, "Making RSA keys." ); Worker.ReportProgress( 0, "Bits size is: " + ShowBits.ToString()); // ulong Loops = 0; while( true ) { if( Worker.CancellationPending ) return; Thread.Sleep( 1 ); // Give up the time slice. Let other things on the server run. // Make two prime factors. // Normally you'd only make new primes when you pay the Certificate // Authority for a new certificate. if( !MakeAPrime( PrimeP, PrimeIndex, 20 )) return; IntegerBase TestP = new IntegerBase(); IntegerBaseMath IntBaseMath = new IntegerBaseMath( IntMath ); string TestS = IntMath.ToString10( PrimeP ); IntBaseMath.SetFromString( TestP, TestS ); string TestS2 = IntBaseMath.ToString10( TestP ); if( TestS != TestS2 ) throw( new Exception( "TestS != TestS2 for IntegerBase." )); if( Worker.CancellationPending ) return; if( !MakeAPrime( PrimeQ, PrimeIndex, 20 )) return; if( Worker.CancellationPending ) return; // This is extremely unlikely. Integer Gcd = new Integer(); IntMath.GreatestCommonDivisor( PrimeP, PrimeQ, Gcd ); if( !Gcd.IsOne()) { Worker.ReportProgress( 0, "They had a GCD: " + IntMath.ToString10( Gcd )); continue; } if( Worker.CancellationPending ) return; // This would never happen since the public key exponent used here // is one of the small primes in the array in IntegerMath that it // was checked against. But it does show here in the code that // they have to be co-prime to each other. And in the future it // might be found that the public key exponent has to be much larger // than the one used here. IntMath.GreatestCommonDivisor( PrimeP, PubKeyExponent, Gcd ); if( !Gcd.IsOne()) { Worker.ReportProgress( 0, "They had a GCD with PubKeyExponent: " + IntMath.ToString10( Gcd )); continue; } if( Worker.CancellationPending ) return; IntMath.GreatestCommonDivisor( PrimeQ, PubKeyExponent, Gcd ); if( !Gcd.IsOne()) { Worker.ReportProgress( 0, "2) They had a GCD with PubKeyExponent: " + IntMath.ToString10( Gcd )); continue; } // For Modular Reduction. This only has to be done // once, when P and Q are made. IntMathNewForP.SetupGeneralBaseArray( PrimeP ); IntMathNewForQ.SetupGeneralBaseArray( PrimeQ ); PrimePMinus1.Copy( PrimeP ); IntMath.SubtractULong( PrimePMinus1, 1 ); PrimeQMinus1.Copy( PrimeQ ); IntMath.SubtractULong( PrimeQMinus1, 1 ); // These checks should be more thorough. if( Worker.CancellationPending ) return; Worker.ReportProgress( 0, "The Index of Prime P is: " + PrimeP.GetIndex().ToString() ); Worker.ReportProgress( 0, "Prime P:" ); Worker.ReportProgress( 0, IntMath.ToString10( PrimeP )); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "Prime Q:" ); Worker.ReportProgress( 0, IntMath.ToString10( PrimeQ )); Worker.ReportProgress( 0, " " ); PubKeyN.Copy( PrimeP ); IntMath.Multiply( PubKeyN, PrimeQ ); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "PubKeyN:" ); Worker.ReportProgress( 0, IntMath.ToString10( PubKeyN )); Worker.ReportProgress( 0, " " ); // Euler's Theorem: // https://en.wikipedia.org/wiki/Euler's_theorem // if x ≡ y (mod φ(n)), // then a^x ≡ a^y (mod n). // Euler's Phi function (aka Euler's Totient function) is calculated // next. // PhiN is made from the two factors: (P - 1)(Q - 1) // PhiN is: (P - 1)(Q - 1) = PQ - P - Q + 1 // If I add (P - 1) to PhiN I get: // PQ - P - Q + 1 + (P - 1) = PQ - Q. // If I add (Q - 1) to that I get: // PQ - Q + (Q - 1) = PQ - 1. // (P - 1)(Q - 1) + (P - 1) + (Q - 1) = PQ - 1 // If (P - 1) and (Q - 1) had a larger GCD then PQ - 1 would have // that same factor too. IntMath.GreatestCommonDivisor( PrimePMinus1, PrimeQMinus1, Gcd ); Worker.ReportProgress( 0, "GCD of PrimePMinus1, PrimeQMinus1 is: " + IntMath.ToString10( Gcd )); if( !Gcd.IsULong()) { Worker.ReportProgress( 0, "This GCD number is too big: " + IntMath.ToString10( Gcd )); continue; } else { ulong TooBig = Gcd.GetAsULong(); // How big of a GCD is too big? if( TooBig > 1234567 ) { // (P - 1)(Q - 1) + (P - 1) + (Q - 1) = PQ - 1 Worker.ReportProgress( 0, "This GCD number is bigger than 1234567: " + IntMath.ToString10( Gcd )); continue; } } Integer Temp1 = new Integer(); PhiN.Copy( PrimePMinus1 ); Temp1.Copy( PrimeQMinus1 ); IntMath.Multiply( PhiN, Temp1 ); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "PhiN:" ); Worker.ReportProgress( 0, IntMath.ToString10( PhiN )); Worker.ReportProgress( 0, " " ); if( Worker.CancellationPending ) return; // In RFC 2437 there are commonly used letters/symbols to represent // the numbers used. So the number e is the public exponent. // The number e that is used here is called PubKeyExponentUint = 65537. // In the RFC the private key d is the multiplicative inverse of // e mod PhiN. Which is mod (P - 1)(Q - 1). It's called // PrivKInverseExponent here. if( !IntMath.IntMathNew.FindMultiplicativeInverseSmall( PrivKInverseExponent, PubKeyExponent, PhiN, Worker )) return; if( PrivKInverseExponent.IsZero()) continue; Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "PrivKInverseExponent: " + IntMath.ToString10( PrivKInverseExponent )); if( Worker.CancellationPending ) return; // In RFC 2437 it defines a number dP which is the multiplicative // inverse, mod (P - 1) of e. That dP is named PrivKInverseExponentDP here. Worker.ReportProgress( 0, " " ); if( !IntMath.IntMathNew.FindMultiplicativeInverseSmall( PrivKInverseExponentDP, PubKeyExponent, PrimePMinus1, Worker )) return; Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "PrivKInverseExponentDP: " + IntMath.ToString10( PrivKInverseExponentDP )); if( PrivKInverseExponentDP.IsZero()) continue; // PrivKInverseExponentDP is PrivKInverseExponent mod PrimePMinus1. Integer Test1 = new Integer(); Test1.Copy( PrivKInverseExponent ); IntMath.Divide( Test1, PrimePMinus1, Quotient, Remainder ); Test1.Copy( Remainder ); if( !Test1.IsEqual( PrivKInverseExponentDP )) throw( new Exception( "Bug. This does not match the definition of PrivKInverseExponentDP." )); if( Worker.CancellationPending ) return; // In RFC 2437 it defines a number dQ which is the multiplicative // inverse, mod (Q - 1) of e. That dQ is named PrivKInverseExponentDQ here. Worker.ReportProgress( 0, " " ); if( !IntMath.IntMathNew.FindMultiplicativeInverseSmall( PrivKInverseExponentDQ, PubKeyExponent, PrimeQMinus1, Worker )) return; if( PrivKInverseExponentDQ.IsZero()) continue; Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "PrivKInverseExponentDQ: " + IntMath.ToString10( PrivKInverseExponentDQ )); if( Worker.CancellationPending ) return; Test1.Copy( PrivKInverseExponent ); IntMath.Divide( Test1, PrimeQMinus1, Quotient, Remainder ); Test1.Copy( Remainder ); if( !Test1.IsEqual( PrivKInverseExponentDQ )) throw( new Exception( "Bug. This does not match the definition of PrivKInverseExponentDQ." )); // Make a random number to test encryption/decryption. Integer ToEncrypt = new Integer(); int HowManyBytes = PrimeIndex * 4; byte[] RandBytes = MakeRandomBytes( HowManyBytes ); if( RandBytes == null ) { Worker.ReportProgress( 0, "Error making random bytes in MakeRSAKeys()." ); return; } if( !ToEncrypt.MakeRandomOdd( PrimeIndex - 1, RandBytes )) { Worker.ReportProgress( 0, "Error making random number ToEncrypt." ); return; } Integer PlainTextNumber = new Integer(); PlainTextNumber.Copy( ToEncrypt ); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "Before encrypting number: " + IntMath.ToString10( ToEncrypt )); Worker.ReportProgress( 0, " " ); IntMath.IntMathNew.ModularPower( ToEncrypt, PubKeyExponent, PubKeyN, false ); if( Worker.CancellationPending ) return; Worker.ReportProgress( 0, IntMath.GetStatusString() ); Integer CipherTextNumber = new Integer(); CipherTextNumber.Copy( ToEncrypt ); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "Encrypted number: " + IntMath.ToString10( CipherTextNumber )); Worker.ReportProgress( 0, " " ); ECTime DecryptTime = new ECTime(); DecryptTime.SetToNow(); IntMath.IntMathNew.ModularPower( ToEncrypt, PrivKInverseExponent, PubKeyN, false ); Worker.ReportProgress( 0, "Decrypted number: " + IntMath.ToString10( ToEncrypt )); if( !PlainTextNumber.IsEqual( ToEncrypt )) { throw( new Exception( "PlainTextNumber not equal to unencrypted value." )); // Because P or Q wasn't really a prime? // Worker.ReportProgress( 0, "PlainTextNumber not equal to unencrypted value." ); // continue; } Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "Decrypt time seconds: " + DecryptTime.GetSecondsToNow().ToString( "N2" )); Worker.ReportProgress( 0, " " ); if( Worker.CancellationPending ) return; // Test the standard optimized way of decrypting: if( !ToEncrypt.MakeRandomOdd( PrimeIndex - 1, RandBytes )) { Worker.ReportProgress( 0, "Error making random number in MakeRSAKeys()." ); return; } PlainTextNumber.Copy( ToEncrypt ); IntMath.IntMathNew.ModularPower( ToEncrypt, PubKeyExponent, PubKeyN, false ); if( Worker.CancellationPending ) return; CipherTextNumber.Copy( ToEncrypt ); // QInv is the multiplicative inverse of PrimeQ mod PrimeP. if( !IntMath.MultiplicativeInverse( PrimeQ, PrimeP, QInv, Worker )) throw( new Exception( "MultiplicativeInverse() returned false." )); if( QInv.IsNegative ) throw( new Exception( "This is a bug. QInv is negative." )); Worker.ReportProgress( 0, "QInv is: " + IntMath.ToString10( QInv )); DecryptWithQInverse( CipherTextNumber, ToEncrypt, // Decrypt it to this. PlainTextNumber, // Test it against this. PubKeyN, PrivKInverseExponentDP, PrivKInverseExponentDQ, PrimeP, PrimeQ, Worker ); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "Found the values:" ); Worker.ReportProgress( 0, "Seconds: " + StartTime.GetSecondsToNow().ToString( "N0" )); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 1, "Prime1: " + IntMath.ToString10( PrimeP )); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 1, "Prime2: " + IntMath.ToString10( PrimeQ )); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 1, "PubKeyN: " + IntMath.ToString10( PubKeyN )); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 1, "PrivKInverseExponent: " + IntMath.ToString10( PrivKInverseExponent )); /* Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, " " ); DoCRTTest( PrivKInverseExponent ); Worker.ReportProgress( 0, "Finished CRT test." ); Worker.ReportProgress( 0, " " ); */ return; // Comment this out to just leave it while( true ) for testing. } }
private void CheckTimer_Tick(object sender, EventArgs e) { // This timer event only gets called when the server isn't otherwise busy. // Even though the timer interval is set to once every 50 milliseconds it // doesn't mean it will get called that often. // It has TestTime to check on how busy it is. if( !IsEnabled ) return; CheckTimer.Stop(); try // for finally { try // for catch { ECTime TestTime = new ECTime(); TestTime.SetToNow(); // 100 clients queued up per timer tick is 2,000 per second max, // assuming the server isn't busy and the timer events get called that often. // But if there were that many clients connecting you'd need more front end // servers to handle the I/O. Or it's a denial of service attack, and you'd // need to deal with that. for( int Count = 0; Count < 100; Count++ ) { if( !IsEnabled ) return; if( Listener.Pending() ) QueueConnectedClient(); else break; } CloseTimedOut(); if( !IsEnabled ) return; FreeClosed(); if( !IsEnabled ) return; ProcessOuterMessages(); if( !IsEnabled ) return; double Seconds = TestTime.GetSecondsToNow(); if( Seconds > 1.0 ) { ShowStatus( " " ); ShowStatus( "**************************************************" ); ShowStatus( "TLS Listener Test time seconds: " + Seconds.ToString( "N0" )); ShowStatus( "Test time:: " + TestTime.ToLocalTimeString()); ShowStatus( "**************************************************" ); ShowStatus( " " ); } } catch( Exception Except ) { ShowStatus( "Exception in CheckTimerTick: \r\n" + Except.Message ); return; } } finally { CheckTimer.Start(); } }
internal bool DecryptWithQInverse( Integer EncryptedNumber, Integer DecryptedNumber, Integer TestDecryptedNumber, Integer PubKeyN, Integer PrivKInverseExponentDP, Integer PrivKInverseExponentDQ, Integer PrimeP, Integer PrimeQ, BackgroundWorker Worker ) { Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "Top of DecryptWithQInverse()." ); // QInv and the dP and dQ numbers are normally already set up before // you start your listening socket. ECTime DecryptTime = new ECTime(); DecryptTime.SetToNow(); // See section 5.1.2 of RFC 2437 for these steps: // http://tools.ietf.org/html/rfc2437 // 2.2 Let m_1 = c^dP mod p. // 2.3 Let m_2 = c^dQ mod q. // 2.4 Let h = qInv ( m_1 - m_2 ) mod p. // 2.5 Let m = m_2 + hq. Worker.ReportProgress( 0, "EncryptedNumber: " + IntMath.ToString10( EncryptedNumber )); // 2.2 Let m_1 = c^dP mod p. TestForDecrypt.Copy( EncryptedNumber ); IntMathNewForP.ModularPower( TestForDecrypt, PrivKInverseExponentDP, PrimeP, true ); if( Worker.CancellationPending ) return false; M1ForInverse.Copy( TestForDecrypt ); // 2.3 Let m_2 = c^dQ mod q. TestForDecrypt.Copy( EncryptedNumber ); IntMathNewForQ.ModularPower( TestForDecrypt, PrivKInverseExponentDQ, PrimeQ, true ); if( Worker.CancellationPending ) return false; M2ForInverse.Copy( TestForDecrypt ); // 2.4 Let h = qInv ( m_1 - m_2 ) mod p. // How many is optimal to avoid the division? int HowManyIsOptimal = (PrimeP.GetIndex() * 3); for( int Count = 0; Count < HowManyIsOptimal; Count++ ) { if( M1ForInverse.ParamIsGreater( M2ForInverse )) M1ForInverse.Add( PrimeP ); else break; } if( M1ForInverse.ParamIsGreater( M2ForInverse )) { M1M2SizeDiff.Copy( M2ForInverse ); IntMath.Subtract( M1M2SizeDiff, M1ForInverse ); // Unfortunately this long Divide() has to be done. IntMath.Divide( M1M2SizeDiff, PrimeP, Quotient, Remainder ); Quotient.AddULong( 1 ); Worker.ReportProgress( 0, "The Quotient for M1M2SizeDiff is: " + IntMath.ToString10( Quotient )); IntMath.Multiply( Quotient, PrimeP ); M1ForInverse.Add( Quotient ); } M1MinusM2.Copy( M1ForInverse ); IntMath.Subtract( M1MinusM2, M2ForInverse ); if( M1MinusM2.IsNegative ) throw( new Exception( "This is a bug. M1MinusM2.IsNegative is true." )); if( QInv.IsNegative ) throw( new Exception( "This is a bug. QInv.IsNegative is true." )); HForQInv.Copy( M1MinusM2 ); IntMath.Multiply( HForQInv, QInv ); if( HForQInv.IsNegative ) throw( new Exception( "This is a bug. HForQInv.IsNegative is true." )); if( PrimeP.ParamIsGreater( HForQInv )) { IntMath.Divide( HForQInv, PrimeP, Quotient, Remainder ); HForQInv.Copy( Remainder ); } // 2.5 Let m = m_2 + hq. DecryptedNumber.Copy( HForQInv ); IntMath.Multiply( DecryptedNumber, PrimeQ ); DecryptedNumber.Add( M2ForInverse ); if( !TestDecryptedNumber.IsEqual( DecryptedNumber )) throw( new Exception( "!TestDecryptedNumber.IsEqual( DecryptedNumber )." )); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "DecryptedNumber: " + IntMath.ToString10( DecryptedNumber )); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "TestDecryptedNumber: " + IntMath.ToString10( TestDecryptedNumber )); Worker.ReportProgress( 0, " " ); Worker.ReportProgress( 0, "Decrypt with QInv time seconds: " + DecryptTime.GetSecondsToNow().ToString( "N2" )); Worker.ReportProgress( 0, " " ); return true; }