SACryptoServiceProvider创建X509Cer

SACryptoServiceProvider创建X509Cer

本文介绍了从RSACryptoServiceProvider创建X509Certificate2失败,并找不到所需的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例代码:

        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;
        }

推荐答案

这是我使用BouncyCastle库的解决方案.

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);

这篇关于从RSACryptoServiceProvider创建X509Certificate2失败,并找不到所需的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 09:54