原文:http://hi.baidu.com/lidhcn/item/5476d292a0710eda1a49df60
1.从磁盘上的证书文件中读取证书数据
unsigned char* pbX509Data; // 证书数据unsigned long ulX509DataLen; // 证书数据长度
2.获取CertContext
PCCERT_CONTEXT pCertContext = CertCreateCertificateContext(X509_ASN_ENCODING, pbX509Data, ulX509DataLen);
3.获取证书信息
pCertContext->pCertInfo->dwVersion; // 证书版本号
CRYPT_INTEGER_BLOB snBlob = pCertContext->pCertInfo->SerialNumber; // 证书SN
CERT_NAME_BLOB issuerBlob = pCertContext->pCertInfo->Issuer; // 证书颁发者
CERT_NAME_BLOB subjectBlob = pCertContext->pCertInfo->Subject; // 证书主题
// 证书有效起始日期
SYSTEMTIME sysTime;
memset(&sysTime, 0, sizeof(sysTime));
FileTimeToSystemTime(&pCertContext->pCertInfo->NotBefore, &sysTime);
char szTime[128] = {0};
sprintf_s(szTime, 128, "%d年%d月%d日%d:%d:%d", sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
// 证书有效终止日期
memset(&sysTime, 0, sizeof(sysTime));
FileTimeToSystemTime(&pCertContext->pCertInfo->NotAfter, &sysTime);
memset(szTime, 0, sizeof(szTime));
sprintf_s(szTime, 128, "%d年%d月%d日%d:%d:%d", sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
4.创建临时密钥容器
HCRYPTPROV hTmpProv = NULL;
CryptAcquireContext(&hTmpProv, "My_Temporary_Container", NULL, PROV_RSA_AES, 0); // NULL表示使用系统默认CSP
5.向容器中导入公钥,获取公钥句柄
HCRYPTKEY hKey = NULL;
CERT_PUBLIC_KEY_INFO certPubKeyInfo = pCertContext->pCertInfo->SubjectPublicKeyInfo;
CryptImportPublicKeyInfo(hTmpProv, X509_ASN_ENCODING|PKCS_7_ASN_ENCODING, &certPubKeyInfo, &hKey);
6.导出公钥(最好采用二次调用方式)
unsigned char* pBuf = NULL;
unsigned long ulBufLen = 0;
CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, pBuf, &ulBufLen);
pBuf = new unsigned char[ulBufLen];
memset(pBuf, 0, ulBufLen);
CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, pBuf, &ulBufLen);
7.获取公钥信息
unsigned char* p = pBuf + sizeof(PUBLICKEYSTRUC);
(*(RSAPUBKEY*)p).bitlen; // 公钥模长(以bit为单位)
(*(RSAPUBKEY*)p).pubexp; // 公钥的e(注意字节顺序)
p += sizeof(RSAPUBKEY); // 公钥的n(注意字节顺序)
8.清理工作
delete[] pBuf;
pBuf = NULL;
CryptDestroyKey(hKey);
CryptReleaseContext(hTmpProv, 0);
CertFreeCertificateContext(pCertContext);