Search code examples
c#encryptioncertificatex509certificatex509certificate2

retrieving X509 certificates from AD Server


Is there any way we can fetch X509 Public Cetrificates using c# from AD Server for Encrypting an Email. Right now I am using the local Store for Picking up the Certificates and Encrypting an Mail.

static public X509Certificate2 GetRecipientCertPublic(string recipientName)
{  
    X509Store storeAddressBook =
        new X509Store(StoreName.AddressBook, StoreLocation.CurrentUser);
    storeAddressBook.Open(OpenFlags.ReadOnly);

    X509Certificate2Collection certColl =
        storeAddressBook.Certificates.Find(X509FindType.FindBySubjectName, recipientName, false);
    storeAddressBook.Close();

    if (certColl.Count != 0)
    {

        return certColl[0];
    }
    else
    {
        return null;
    }
}

As i see the behaviour in Outlook is different. Even if the public certificate of the Recipeint is not Present in the local Machines Certificate Manager. it is able to pick up the public certificate from centeral server of the organization or the Ad Server (i am not very sure about it) and send the encrypted mail.


Solution

  • // Where ##### is the name of your AD server
    DirectoryEntry de = new DirectoryEntry("LDAP://#####");
    DirectorySearcher dsearch = new DirectorySearcher(de);
    
    //Search how you want.  Google "LDAP Filter" for more.
    dsearch.Filter = "(cn=#####)"; 
    SearchResultCollection rc = dsearch.FindAll();
    X509Certificate stt = new X509Certificate();
    
    foreach (SearchResult r in rc)
    {
        if (r.Properties.Contains("userCertificate"))
        {
            // This is hard coded to the first element.
            // Some users may have multiples.  Use ADSI Edit to find out more.
            Byte[] b = (Byte[])r.Properties["userCertificate"][0];
            X509Certificate cert1 = new X509Certificate(b);
        }
    }