I want to create a pfx file from keys created by RSACryptoServiceProvider . I tried:
certificate.PrivateKey = rsa as AsymmetricAlgorithm;
which is the reverse of:
rsa = (RSACryptoServiceProvider)certificate.PrivateKey;
which seems to work (the second, that is). But got the following error:
m_safeCertContext is an invalid handle.
I tried some things using RSAParameters - but to no avail.
You can use Bouncy Castle to do it:
private static byte[] MergePFXFromPrivateAndCertificate(RSAParameters privateKey, X509Certificate2 certificate, string pfxPassPhrase)
{
RsaPrivateCrtKeyParameters rsaParam = new RsaPrivateCrtKeyParameters(
ParseAsUnsignedBigInteger(privateKey.Modulus),
ParseAsUnsignedBigInteger(privateKey.Exponent),
ParseAsUnsignedBigInteger(privateKey.D),
ParseAsUnsignedBigInteger(privateKey.P),
ParseAsUnsignedBigInteger(privateKey.Q),
ParseAsUnsignedBigInteger(privateKey.DP),
ParseAsUnsignedBigInteger(privateKey.DQ),
ParseAsUnsignedBigInteger(privateKey.InverseQ)
);
Org.BouncyCastle.X509.X509Certificate bcCert = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(certificate.RawData);
MemoryStream p12Stream = new MemoryStream();
Pkcs12Store p12 = new Pkcs12Store();
p12.SetKeyEntry("key", new AsymmetricKeyEntry(rsaParam), new X509CertificateEntry[] { new X509CertificateEntry(bcCert) });
p12.Save(p12Stream, pfxPassPhrase.ToCharArray(), new SecureRandom());
return p12Stream.ToArray();
}
private static BigInteger ParseAsUnsignedBigInteger(byte[] rawUnsignedNumber)
{
return new BigInteger(1, rawUnsignedNumber, 0, rawUnsignedNumber.Length);
}
You will need the following namespaces:
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.