Sunday, 11 September 2016

How to export Private Key from X509Certificate2 in C#?

First of all make sure you have private key associated with public key of certificate.
That you may found using .HasPrivateKey property.

X509Certificate2 MyRootCAcert = new X509Certificate2( "yourcert.pfx", "password");

If you are sure you have private key with cert, you may use following key to use private key

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)MyRootCAcert.PrivateKey;
AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(rsa);
var myCAprivateKey = keyPair.Private;

Key not valid for use in specified state while exporting Private Key from X509Certificate2.

Error you may found CryptographicException
key not valid for use in specified state
Make sure you have passed 3rd argument as X509KeyStorageFlags.Exportable

X509Certificate2 MyRootCAcert = new X509Certificate2( "yourcert.pfx", "password", X509KeyStorageFlags.Exportable);