I have a requirement from my Client to Install .cer file without a private key and export it to a .pfx file with Private key using C#
I tried all the different solutions provided which allowed me to export .cer to .pfx but without a key and .pfx file is empty
string file = @"C:\TestCert1.cer";
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
X509Certificate2 test = new X509Certificate2(X509Certificate2.CreateFromCertFile(file));
string name = test.SerialNumber;
store.Certificates.Insert(0, test);
store.Add(test);
store.Close();
byte[] certData = store.Certificates.Export(X509ContentType.Pfx, "MyPassword");
File.WriteAllBytes(@"C:\MyCert.pfx", certData);
This part is OK:
string file = @"C:\TestCert1.cer";
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
Instead of
X509Certificate2 test = new X509Certificate2(X509Certificate2.CreateFromCertFile(file));
you want the much simpler
X509Certificate2 test = new X509Certificate2(file);
Not sure what this was for, you never used the variable.
string name = test.SerialNumber;
This line does nothing useful. (store.Certificates
returns a new collection that's a copy of the state of the store at that time... you add to that collection then let it fall out of scope).
store.Certificates.Insert(0, test);
This one actually adds the cert to the store, so it's OK, except not necessary for your goals.
store.Add(test);
So now you close the store then try to export it. Which doesn't make sense, the closed store's Certificates
property always returns an empty collection. (It should have thrown, but that ship sailed long ago).
store.Close();
byte[] certData = store.Certificates.Export(X509ContentType.Pfx, "MyPassword");
File.WriteAllBytes(@"C:\MyCert.pfx", certData);
What you probably want is to open the file, then look through the store and see if there's a match, and export the match.
using (X509Certificate2 filter = new X509Certificate2(file))
using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
// The bytes making up the certificate, in DER/binary form.
byte[] filterRawData = filter.RawData;
foreach (X509Certificate2 storeCert in store.Certificates)
{
if (storeCert.RawData.SequenceEquals(filterRawData))
{
File.WriteAllBytes(outputFileName, storeCert.Export(X509ContentType.Pfx, password));
return;
}
}
}
Console.WriteLine("No match found...");