1

How do I generate random RSA public and private keys (RSAParameters) using RSACryptoServiceProvider class? Each time I create a new instance of RSACryptoServiceProvider, I end up exporting the same keys.

Thanks

Maksim Skurydzin
  • 10,301
  • 8
  • 40
  • 53

2 Answers2

4

I did some test on the following code, and the exported parameters are always different:

var rsaAlgo1 = new RSACryptoServiceProvider();
var rsaAlgo2 = new RSACryptoServiceProvider();

var xml1 = rsaAlgo1.ToXmlString(true);
var xml2 = rsaAlgo2.ToXmlString(true);

if (xml1 != xml2)
{
   // it always goes here...
}
digEmAll
  • 56,430
  • 9
  • 115
  • 140
  • 1
    This code works, but it is a very dangerous style. The `Create()`-method you are calling is actually a static method on the abstract `RSA`-class (the superclass to `RSACryptoServiceProvider`) and creates an instance of the default implementation of the `RSA`-class. On most systems this will be `RSACryptoServiceProvider` - but not on all. A better style would be either `var rsa = RSA.Create()` or `var rsa = new RSACryptoServiceProvider`. – Rasmus Faber Nov 21 '10 at 18:32
  • 1
    Note that for practical use you should specify a key size (e.g. 2048 bits) instead of using the default constructor. – CodesInChaos Oct 14 '14 at 09:36
  • Randomness in Cryptography can't be checked by a simple comparison. It has to meet four requirements. Check them out http://www.cs.ucsb.edu/~koc/cren/docs/w06/rng.pdf – Nayef Jan 15 '15 at 08:12
0

Using the following code you should never get all the same keys out

var rsa = new RSACryptoServiceProvider();
var rsaParams = rsa.ExportParameters(true);

However you should note that the Exponent key can be the same and if often is 65537(0x010001)

"Choose an integer e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1; i.e., e and φ(n) are coprime. e is released as the public key exponent. e having a short bit-length and small Hamming weight results in more efficient encryption – most commonly 216 + 1 = 65,537. However, much smaller values of e (such as 3) have been shown to be less secure in some settings." RSA wiki