How to Install a PFX Certificate through Code?

IIS

Go to IIS > Server Certificates > Export Certificate

C#

Install Certificate to Current User.

X509Certificate2 certificate = new X509Certificate2(“C:\\Certificates\\IISExported.pfx”, “Password”);
X509Store xstore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
xstore.Open(OpenFlags.ReadWrite);
xstore.Add(certificate);
xstore.Close();

Testing C#

Try getting the Certificate back.

X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, false);
if (col == null || col.Count == 0)
{
     Console.WriteLine(“ERROR: Certificate not found with thumbprint”);
}
else
     Console.WriteLine(“Found: ” + col[0].FriendlyName);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s