Friday, February 24, 2012

How to export loggedin user`s certificate programmatically

Problem 
You need to export of currently logged in user certificate in programmatic way.

Solution 

using System;

 
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Security.Cryptography.X509Certificates;
    using System.Net;
    using System.Diagnostics;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class CertificateHalper
    {
       public static  X509Certificate userCert = null;
        public static X509Certificate GetClientCertificate(string username)
        {
          // USERNAME= Active Directory User name , Use Environment.UserName to get user name
            if (userCert == null)
            {
                X509Store certStore = new X509Store(StoreLocation.CurrentUser);
                certStore.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certList = certStore.Certificates;


                foreach (X509Certificate cert in certList)
                {
                    if (cert.Subject == "CN=" + username)
                    {
                        userCert = cert;
                    }
                }

            }
          
            return userCert;

        }
    }

 



No comments:

Post a Comment