Search code examples
c#x509certificatevpnx509certificate2

How do I import this Cert Properly?


I'm running into a strange issue when importing certs using c# x509Certs Library, the cert/key and the CA cert are seemingly imported properly (If I open MMC and snap-in a local computer certificates store I see them in their respective stores Trusted Root Certificates and Personal).

The Trust root certificate seems to be working fine. Here's how I know the personal cert isn't being imported properly. The certs are from a VPN provider, and when I import them manually everything works fine. When I use my little tool, I get a "IKE can't find valid machine certificate." Here's how I'm importing it:

X509Certificate2 certificate = new X509Certificate2();
byte[] rawCertificateData = File.ReadAllBytes(@"Cert.p12");
certificate.Import(rawCertificateData, "password",  X509KeyStorageFlags.PersistKeySet);

X509Store store = new X509Store(StoreName.Root,
                                         StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
store.Add(CACert); 
store.Close();


X509Store store1 = new X509Store(StoreName.My,
                                         StoreLocation.LocalMachine);
store1.Open(OpenFlags.ReadWrite);
store1.Add(certificate);
store1.Close();

Now after using my tool, if I got to mcc I see the personal cert/key but I get that "can't find machine certificate error" and if I reimport the personal cert everything works fine. So again I think the Personal cert is the issue here. Any ideas?


Just to clarify, when I import Cer.p12 and CACert.cer using MMC everything works fine.

When using my tool, the Cer.p12 has an import issue. Reimporting this seems to fix the issue.


Solution

  • yacoub-massad's comment on my question was a little obscure but I did mange to get some use of it, I realize my problem after reading his VB code.

    X509Certificate2 certificate = new X509Certificate2();
    byte[] rawCertificateData = File.ReadAllBytes(@"Cert.p12");
    certificate.Import(rawCertificateData, "password", X509KeyStorageFlags.MachineKeySet);
    

    The only thing I changed between my previous code and this was .PersistKeySet > .MachineKeySet