public static void CreateAsymetricKey(int strength, out string privateKey, out string publicKey) { RsaKeyPair keyPair = RSA.GenerateKeyPair(strength); privateKey = keyPair.PrivateKey.ToXmlString(); publicKey = keyPair.PublicKey.ToXmlString(); }
public static RsaKeyPair GenerateKeyPair(int strength, int certainity, BigInteger publicExponent) { BigInteger p, q, n, d, e, pSub1, qSub1, phi; // This is cryptographic stuff, we want to use the secure random provider Random rand = RandomGenerator.GetSecureRandomGenerator(); // // p and q values should have a length of half the strength in bits // int pbitlength = (strength + 1) / 2; int qbitlength = (strength - pbitlength); e = publicExponent; // // Generate p, prime and (p-1) relatively prime to e // for (; ;) { p = new BigInteger(pbitlength, certainity, rand); if (e.Gcd(p.Subtract(BigInteger.One)).Equals(BigInteger.One)) { break; } } // // Generate a modulus of the required length // for (; ;) { // Generate q, prime and (q-1) relatively prime to e, // and not equal to p // for (; ;) { q = new BigInteger(qbitlength, certainity, rand); if (e.Gcd(q.Subtract(BigInteger.One)).Equals(BigInteger.One) && !p.Equals(q)) { break; } } // // calculate the modulus // n = p.Multiply(q); if (n.BitLength() == strength) { break; } // // if we Get here our primes aren't big enough, make the largest // of the two p and try again // p = p.Max(q); } pSub1 = p.Subtract(BigInteger.One); qSub1 = q.Subtract(BigInteger.One); phi = pSub1.Multiply(qSub1); // // calculate the private exponent // d = e.ModInverse(phi); // // calculate the CRT factors // BigInteger dP, dQ, qInv; dP = d.Remainder(pSub1); dQ = d.Remainder(qSub1); qInv = q.ModInverse(p); RsaKey publicKey = new RsaKey(false, n, e); RsaPrivateKey privateKey = new RsaPrivateKey(n, e, d, p, q, dP, dQ, qInv); RsaKeyPair pair = new RsaKeyPair(privateKey, publicKey); return(pair); }