8

Sample code:

        CspParameters cspParameters = new CspParameters();
        cspParameters.ProviderType = 1; // PROV_RSA_FULL

        // Create the crypto service provider, generating a new
        // key.
        mRsaCSP = new RSACryptoServiceProvider(mDefaultKeyLength, cspParameters);
        mRsaCSP.PersistKeyInCsp = true;
        RSAParameters privateKey = mRsaCSP.ExportParameters(true);


        byte[] rsaBytes = mRsaCSP.ExportCspBlob(true);

        try
        {
            X509Certificate2 cert = new X509Certificate2(rsaBytes);                
            mKeyDataPfx = Convert.ToBase64String(cert.Export(X509ContentType.Pkcs12, password));
        }
        catch (Exception ce)
        {
            string error = ce.Message;
        }
Jon Grant
  • 11,369
  • 2
  • 37
  • 58
arunpereira
  • 582
  • 5
  • 13
  • A RSA key is not directly compatible with a X509 Certificate. A X509 Certificate needs to have the key signed by an issuer, even if it is self-signed. Can you tell us what you are actually trying to accomplish? Are you trying to dynamically create a X509 certificate in code? – Phil Bolduc Feb 04 '12 at 18:32
  • 1
    Yes. That is exactly what I am trying to do. The idea is that I have old RSA certificates stored as string with RSACryptoServiceProvider.ToXmlString(true). Those would need to be read in and exported as PFX files. New RSA certificates would need to be generated and stored as PFX files. – arunpereira Feb 04 '12 at 18:50
  • I suggest you check out Bouncy Castle .NET source code and examples. I think the example bccrypto-net-1.7-src\csharp\crypto\test\src\pkcs\examples\PKCS12Example.cs should get you started. http://www.bouncycastle.org/csharp/ – Phil Bolduc Feb 04 '12 at 20:11

1 Answers1

3

Here is my solution, using the BouncyCastle library.

// create the RSA key from an XML string
RSACryptoServiceProvider key = new RSACryptoServiceProvider();
key.FromXmlString(keyTextBox.Text);

// convert to BouncyCastle key object
var keypair = DotNetUtilities.GetRsaKeyPair(key);

var gen = new X509V3CertificateGenerator();

string certName = Path.GetFileNameWithoutExtension(fileName);
var name = new X509Name("CN=" + certName);
var serial = BigInteger.ProbablePrime(120, new Random());

gen.SetSerialNumber(serial);
gen.SetSubjectDN(name);
gen.SetIssuerDN(name);
gen.SetNotAfter(DateTime.Now.AddYears(10));
gen.SetNotBefore(DateTime.Now);
gen.SetSignatureAlgorithm("MD5WithRSA");
gen.SetPublicKey(keypair.Public);

// generate the certificate
var newCert = gen.Generate(keypair.Private);
// convert back to .NET certificate
var cert = DotNetUtilities.ToX509Certificate(newCert);
// export as byte array
byte[] certData = cert.Export(X509ContentType.Pfx);

File.WriteAllBytes(fileName, certData);
Jon Grant
  • 11,369
  • 2
  • 37
  • 58