private void BuildKeys() { //Make a call to Generate_Primes. BigInteger P = new BigInteger(m_RSAParams.P); BigInteger Q = new BigInteger(m_RSAParams.Q); //Exponent. This needs to be a number such that the //GCD of the Exponent and Phi is 1. The larger the exp. //the more secure, but it increases encryption time. BigInteger E = new BigInteger(m_RSAParams.E); BigInteger N = new BigInteger(0); //Public and Private Key Part (Modulus) BigInteger D = new BigInteger(0); //Private Key Part BigInteger DP = new BigInteger(0); BigInteger DQ = new BigInteger(0); BigInteger IQ = new BigInteger(0); BigInteger Phi = new BigInteger(0); //Phi //Make sure P is greater than Q, swap if less. if (P < Q) { BigInteger biTmp = P; P = Q; Q = biTmp; biTmp = null; m_RSAParams.P = P.getBytesRaw(); m_RSAParams.Q = Q.getBytesRaw(); } //Calculate the modulus N = P * Q; m_RSAParams.N = N.getBytesRaw(); //Calculate Phi Phi = (P - 1) * (Q - 1); m_RSAParams.Phi = Phi.getBytesRaw(); //Make sure our Exponent will work, or choose a larger one. while (Phi.gcd(E) > 1) { //If the GCD is greater than 1 iterate the Exponent E = E + 2; //Also make sure the Exponent is prime. while (!E.isProbablePrime()) { E = E + 2; } } //Make sure the params contain the updated E value m_RSAParams.E = E.getBytesRaw(); //Calculate the private exponent D. D = E.modInverse(Phi); m_RSAParams.D = D.getBytesRaw(); //Calculate DP DP = E.modInverse(P - 1); m_RSAParams.DP = DP.getBytesRaw(); //Calculate DQ DQ = E.modInverse(Q - 1); m_RSAParams.DQ = DQ.getBytesRaw(); //Calculate InverseQ IQ = Q.modInverse(P); m_RSAParams.IQ = IQ.getBytesRaw(); m_KeyLoaded = true; m_isBusy = false; OnKeysGenerated(this); }
//*********************************************************************** // Generates a positive BigInteger that is probably prime. // Overloaded to use the isProbablePrime method with no confidence value //*********************************************************************** internal static BigInteger genPseudoPrime(int bits, Random rand) { BigInteger result = new BigInteger(); bool done = false; while (!done) { result.genRandomBits(bits, rand); result.data[0] |= 0x01; // make it odd // prime test done = result.isProbablePrime(); } return result; }