从AD Server检索X509证书

时间:2012-03-19 13:52:46

标签: c# encryption certificate x509certificate x509certificate2

我们是否可以使用AD服务器中的c#来获取X509公共证书来加密电子邮件。 现在我正在使用本地商店提取证书和加密邮件。

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;
    }
}

正如我所看到的,Outlook中的行为是不同的。即使Recipeint的公共证书不在本地机器证书管理器中。它能够从组织的中心服务器或广告服务器(我不是很确定)中获取公共证书并发送加密邮件。

1 个答案:

答案 0 :(得分:5)

// 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);
    }
}