Thursday, December 18, 2014

How to solve problem "Cannot find the requested object." while create an X509Certificate2 object?


It throws this exception for following line:
X509Certificate2 certificate = new X509Certificate2(@"c:\temp\server.pvk", "password");

It means: the certificate file is not valid.
The most common reason is:
Need pvkimprt tool to generate PFX files

Reference:
http://msdn.microsoft.com/en-us/library/ms148420(v=vs.110).aspx
This constructor creates a new X509Certificate2 object using a certificate file name and a password needed to access the certificate. It is used with PKCS12 (PFX) files that contain the certificate's private key. Calling this constructor with the correct password decrypts the private key and saves it to a key container.

Following are the steps to generate X509Certificate2

"C:\Program Files (x86)\Windows Kits\8.1\bin\x64\makecert" -r -pe -n "CN=Test" -sky exchange c:\temp\server.cer -sv c:\temp\server.pvk -sr currentuser
"C:\Program Files (x86)\Windows Kits\8.1\bin\x64\cert2spc"  c:\temp\server.cer server.spc
pvkimprt -pfx server.spc server.pfx