您的位置:首页 > 大数据 > 人工智能

Using CAPICOM to obtain an SSL Certificate

2007-08-16 17:32 369 查看
using System;
using System.Collections;
using System.Security.Cryptography.x509Certificates;
using interop.capicom;

namespace CAPIComWrapper
{
/// <summary>
/// Provides methods to interact with Windows Certificate stores.
/// </summary>
public class CertificateManager
{
/// <summary>
/// Searches for and returns a particular X509 certificate.
/// </summary>
/// <param name="SearchString">A full or partial certificate name</param>
/// <returns>An instance of the X509Certificate class.</returns>
public static X509Certificate Get(string SearchString)
{
string storeName = "My"; // "My" indicates the .Default store
StoreClass oStore;
Certificates oCerts;
X509Certificate foundcert = null; System;

// get a reference to the LOCAL MACHINE certificate store
oStore = new StoreClass();
oStore.Open(
CAPICOM_STORE_LOCATION.CAPICOM_LOCAL_MACHINE_STORE,
storeName,
CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY |
CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_ONLY);

// Get a list of all certificates in the store
oCerts = (Certificates)oStore.Certificates;

// get a list of only the matching certificates
oCerts = (Certificates)oCerts.Find(
CAPICOM_CERTIFICATE_FIND_TYPE.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME,
SearchString,
false);

// do we have any certs?
if(oCerts.Count > 0)
{
// reference the first certificate
Certificate firstcert = (Certificate)oCerts[1] ;

// get a certificate context from that cert
ICertContext iCertCntxt = (ICertContext) firstcert;

// now get a pointer to the context
int certcntxt = iCertCntxt.CertContext ;

// turn the int pointer into a managed IntPtr
IntPtr hCertCntxt = new IntPtr(certcntxt);

// was all of this successful?
if(hCertCntxt != IntPtr.Zero)
{
// create an X509Certificate from the cert context
foundcert = new X509Certificate(hCertCntxt);
}

// free the certificate context
iCertCntxt.FreeContext(certcntxt);
}
else
{
foundcert = null;
}
return foundcert;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐