获取 Schannel 的证书
以下示例演示获取包含证书 的 CERT_CONTEXT 结构的步骤;应选择适合应用程序的证书和证书存储。
此示例演示如何通过 SCHANNEL_CRED 结构打开 证书存储和 查找将传递给 AcquireCredentialsHandle 函数的 证书 。
#include <windows.h>
#include <stdio.h>
#pragma comment(lib, "crypt32.lib")
#define MACHINE_NAME "example server"
PCCERT_CONTEXT getServerCertificate ()
{
HCERTSTORE hMyCertStore = NULL;
PCCERT_CONTEXT aCertContext = NULL;
//-------------------------------------------------------
// Open the My store, also called the personal store.
// This call to CertOpenStore opens the Local_Machine My
// store as opposed to the Current_User's My store.
hMyCertStore = CertOpenStore(CERT_STORE_PROV_SYSTEM,
X509_ASN_ENCODING,
0,
CERT_SYSTEM_STORE_LOCAL_MACHINE,
L"MY");
if (hMyCertStore == NULL)
{
printf("Error opening MY store for server.\n");
goto cleanup;
}
//-------------------------------------------------------
// Search for a certificate with some specified
// string in it. This example attempts to find
// a certificate with the string "example server" in
// its subject string. Substitute an appropriate string
// to find a certificate for a specific user.
aCertContext = CertFindCertificateInStore(hMyCertStore,
X509_ASN_ENCODING,
0,
CERT_FIND_SUBJECT_STR_A,
MACHINE_NAME, // use appropriate subject name
NULL
);
if (aCertContext == NULL)
{
printf("Error retrieving server certificate.");
goto cleanup;
}
cleanup:
if(hMyCertStore)
{
CertCloseStore(hMyCertStore,0);
}
return aCertContext;
}