获取UKEY证书内容,证书名和证书序列号

#pragma once

#include
#include
#include
#include
#include 
using namespace std;

#pragma comment(lib,"Crypt32")
#pragma comment(lib,"Shlwapi.lib")
#pragma comment(lib,"atls.lib")
#pragma comment(lib,"comsuppw.lib")


std::string GetUKeyCSP()
{
	return "SmartCard RSA CSP";
}

//______________________________________________
// 去除指定字符  
// 下面的代码用于字符串替换  
static char* trim(char *str, char chr){  
	return (*str==0)?str:(((*str!=chr)?(((trim(str+1, chr)-1)==str)?str:(*(trim(str+1,chr)-1)=*str,*str=chr,trim(str+1,chr))):trim(str+1,chr)));  
} 

// 删除字符串中的指定字符, 返回字符串  
static char *trimString(char *str, char chr)  
{  
#pragma   warning( disable: 4996 )   
	return lstrcpyA(str, trim(str, chr));  
#pragma   warning( default: 4996 )  
}  

// 提取X509证书序列号,返回与IE看到的证书序列一致(去掉空格) sn是48的数组。 
static BOOL parseX509CertSerialNumber(PCCERT_CONTEXT  hCert, char* sn)  
{  
	int      i, len;  
	char     c0, c1;  
	BOOL     bResult;  
	CRYPT_INTEGER_BLOB  SerialNumber;     
	char    *s;     

	// 取得要解码的信息尺寸  
	bResult = CryptFormatObject(  
		hCert->dwCertEncodingType,     
		0,     
		0,     
		NULL,     
		0,     
		hCert->pCertInfo->SerialNumber.pbData,  
		hCert->pCertInfo->SerialNumber.cbData,  
		NULL,  
		&SerialNumber.cbData);  

	if (!bResult)  
		return FALSE;  

	// 分配解码数据存放  
	SerialNumber.pbData = (BYTE *) malloc(SerialNumber.cbData);  

	// 解码数据  
	bResult = CryptFormatObject(  
		hCert->dwCertEncodingType,  
		0,     
		0,     
		NULL,     
		0,     
		hCert->pCertInfo->SerialNumber.pbData,  
		hCert->pCertInfo->SerialNumber.cbData,  
		SerialNumber.pbData ,     
		&SerialNumber.cbData);  
	if (!bResult){  
		free(SerialNumber.pbData);  
		return FALSE;  
	}  

	s = (char*) malloc(48);  
	s = ::_com_util::ConvertBSTRToString((BSTR)SerialNumber.pbData);  
	lstrcpyA(sn, s);  
	free(s);  
	free(SerialNumber.pbData);  

	// 去除空格  
	trimString(sn, 32);  

	// 颠倒字符串  
	len = (int)strlen(sn);  

	for(i=0; i= pCertContext->cbCertEncoded && pCert)
							{
								*pdwCertLen = pCertContext->cbCertEncoded;
								memcpy(pCert,pCertContext->pbCertEncoded,pCertContext->cbCertEncoded);		
							}
							else
							{
								*pdwCertLen = pCertContext->cbCertEncoded;
								dwErr = 9;
								goto end;
							}

							CertFreeCertificateContext(pCertContext);
						}//end if
					}
					LocalFree(pbCert);
				CryptDestroyKey(hKey);
				hKey = NULL;
			}
		}

		CryptReleaseContext(hProv, 0);
		hProv = NULL;
	}

end:

	if (hKey)
		CryptDestroyKey(hKey);
	if (hProv)
		CryptReleaseContext(hProv, 0);

	return dwErr;
}

你可能感兴趣的:(信息安全)