Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

X509Certificate.Export Method

Tags:

c#

I try export cert .pfx :

string certPath = "D:\\cert.pfx";
cert = new X509Certificate2(certPath, "pass");

byte[] certData = cert.Export(X509ContentType.Pfx,"pass"); /// **error in this line** 

X509Certificate newCert = new X509Certificate(certData,"pass");

But it finish with this error :

Key not valid for use in specified state.

Can somebody help me ?? Any solution as export certificate from store ??


1 Answers

I think that you were unable to export the private key because the constructor you have used to create the certificate X509Certificate2(filePath, password) does not mark the resulting certificate as exportable. I suggest to use one of the overloaded constructors that allows you to specify the exportable flag - X509KeyStorageFlags.Exportable, for example X509Certificate2(filePath, password, X509KeyStorageFlags.Exportable).

Details on available constructor overloads for the X509Certificate2 and other X509KeyStorageFlags on MSDN Library.

Also you should check the X509Certificate2.HasPrivateKey property to make sure that you have a private key associated with the certificate.

like image 107
andrei m Avatar answered Jul 04 '26 23:07

andrei m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!