Saturday, January 9, 2010

Programmatically install an X.509 certificate with a private key

@YaronNaveh

This c# snippet will install an X.509 certificate with a private key into your windows certificates store:


public static void InstallCertificate(string path, string password)
{
   var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
   store.Open(OpenFlags.ReadWrite);

  try
  {
     X509Certificate2 cert;

     cert = new X509Certificate2(
           path,
           password,
           X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

     store.Add(cert);
  }
  finally
  {
     store.Close();
  }
}

@YaronNaveh

What's next? get this blog rss updates or register for mail updates!

3 comments:

Sahan Arampath said...

Hey
Nice one
Keep it up...

Yaron Naveh said...

Thanks Sahan...

Mitesh Patel said...

This installs certificate successfully into Personal Store of Local Machine successfully. But when I opens Manage Private Keys option for private key in personal store, it gives "no keys found for certificate" error.