c++ winhttp通过https双向认证

不喜欢看下面内容的tx可以直接下载源代码;http://download.csdn.net/detail/sohu_2011/9551472
代码中的ca.p12放到与exe相同目录下,并且应该是自己生产的;




总结:
两个关键点:
1 win下如何加载fpx格式的客户端认证证书,并用于https认证
2 如何通过winhttp进行SSL certificate


主要内容:
一 加载fpx格式证书
windows系统中,我了解的是只能安装pfx格式的客户端证书,如果是pem格式的,可以通过openssl命令转化为fpx格式;
所以,通过windows api只能加载pfx格式的证书;同样比较奇葩的是windows api只能从CertStore中选择证书;没有直接
加载pfx文件的api,所以,要加载证书需要绕个弯:
1 从pfx文件读取数据,填充CRYPT_DATA_BLOB数据结构;
2 根据CRYPT_DATA_BLOB数据结构,通过PFXImportCertStore创建临时的CertStore
3 枚举临时CertStore中的证书,一个个尝试,看看是不是想要的证书
代码如下:
//load and set ca
TCHAR szPath[256] = {0};
::GetModuleFileName(NULL, szPath, 255);
(_tcsrchr(szPath, _T('\\')))[1] = 0; 


CString strFile(szPath);
strFile.Append(_T("ca.p12"));


CFile file;
if(!file.Open(strFile, CFile::modeRead)) 
{
_tprintf(_T("Open ca file error %d\n"), ::GetLastError());
goto END;
}


std::vector clientPfx(file.GetLength(), 0);
file.Read(&clientPfx[0], file.GetLength());


file.Close();


// Convert a .pfx or .p12 file image to a Certificate store
CRYPT_DATA_BLOB PFX;
PFX.pbData= (BYTE *)&clientPfx[0];
PFX.cbData= clientPfx.size();


HCERTSTORE pfxStore= ::PFXImportCertStore( &PFX, pszPassWord, 0 );
if ( NULL == pfxStore )
{
_tprintf(_T("PFXImportCertStore error %d\n"), ::GetLastError());
goto END;
}


// Extract the certificate from the store and pass it to WinHttp
PCCERT_CONTEXT pcontext= NULL, clientCertContext = NULL;
while ( pcontext = ::CertEnumCertificatesInStore( pfxStore, pcontext ) ){
clientCertContext= ::CertDuplicateCertificateContext( pcontext ); // CertEnumCertificatesInStore frees its passed in pcontext !


BOOL stat= ::WinHttpSetOption( hRequest, WINHTTP_OPTION_CLIENT_CERT_CONTEXT, (LPVOID)clientCertContext, sizeof(CERT_CONTEXT) );
if ( FALSE == stat ) 
{
                    _tprintf(_T("WinHttpSetOption error %d\n"), ::GetLastError());


CertCloseStore(pfxStore,0);
       CertFreeCertificateContext(clientCertContext);


   goto END;
}
else
{
break;//success
}
}


CertCloseStore(pfxStore,0);
CertFreeCertificateContext(clientCertContext);
            
hRequest是通过WinHttpOpenRequest返回的句柄,注意这是个句柄,意味着所有与server端交互的任何设定都可以通过它进行,比如添加http头部选项,
也包括设定CertContext;window编程就是什么都通过句柄来,句柄下面有一堆东西,同时也一定存在一系列api还设定这堆东西,例如WinHttpSetOption( hRequest,...)之流;
上面的设定好之后,下面就是与server交互了;


二 与server进行ssl通信
上面有个hRequest,意味着request已经有了,下面就是发送这个request,通过WinHttpSendRequest;
主要代码如下:
// Certain circumstances dictate that we may need to loop on WinHttpSendRequest
// hence the do/while
bool retry = false;
int result = NO_ERROR;
do
{
retry = false;
result = NO_ERROR;


// no retry on success, possible retry on failure
if(WinHttpSendRequest(
hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS,
0,
0,
0,
0,
NULL
) == FALSE)
{
result = GetLastError();


// (1) If you want to allow SSL certificate errors and continue
// with the connection, you must allow and initial failure and then
// reset the security flags. From: "HOWTO: Handle Invalid Certificate
// Authority Error with WinInet"
// http://support.microsoft.com/default.aspx?scid=kb;EN-US;182888
if(result == ERROR_WINHTTP_SECURE_FAILURE)
{
DWORD dwFlags =
SECURITY_FLAG_IGNORE_UNKNOWN_CA |
SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE |
SECURITY_FLAG_IGNORE_CERT_CN_INVALID |
SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;


if(WinHttpSetOption(
hRequest,
WINHTTP_OPTION_SECURITY_FLAGS,
&dwFlags,
sizeof(dwFlags)))
{
retry = true;
}
}
// (2) Negotiate authorization handshakes may return this error
// and require multiple attempts
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa383144%28v=vs.85%29.aspx
else if(result == ERROR_WINHTTP_RESEND_REQUEST)
{
retry = true;
}
}
else
{
bResults = TRUE;
}
} while(retry);
}
        
为什么要重试,因为如果server端的证书不是CA机构颁发的,WinHttpSendRequest会返回错误,这时候就需要WinHttpSetOption设定来忽略这些错误;

然后重新WinHttpSendRequest;


源码:

		// TODO: code your application's behavior here.

		LPCTSTR pszHost = _T("www.myweb.net");
		LPCTSTR pszPort =_T("9999");
		LPCTSTR fileURL = _T("/BookFileSource/book file.xml");
		LPCTSTR pszPassWord = _T("testpassword");

		DWORD dwSize = 0;
		DWORD dwDownloaded = 0;
		LPSTR pszOutBuffer;
		BOOL  bResults = FALSE;
		HINTERNET  hSession = NULL,	hConnect = NULL, hRequest = NULL;

		LPCTSTR szAcceptTypes[] = {_T("text/*"),NULL};

		// Use WinHttpOpen to obtain a session handle.
		hSession = WinHttpOpen( L"WinHTTP/1.0",  
			WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
			WINHTTP_NO_PROXY_NAME, 
			WINHTTP_NO_PROXY_BYPASS, 0 );
		if(!hSession) _tprintf(_T("WinHttpOpen error %d\n"), ::GetLastError());

		// Specify an HTTP server.
		if( hSession )
			hConnect = WinHttpConnect( hSession, pszHost,
			_ttoi(pszPort), 0 );

		if(!hConnect) _tprintf(_T("WinHttpConnect error %d\n"), ::GetLastError());

		// Create an HTTP request handle.
		if( hConnect )
			hRequest = WinHttpOpenRequest( hConnect, L"GET", fileURL,
			NULL, WINHTTP_NO_REFERER, 
			szAcceptTypes, 
			WINHTTP_FLAG_SECURE);

		if(!hRequest) _tprintf(_T("WinHttpOpenRequest error %d\n"), ::GetLastError());

		if(hRequest)
		{			
			
			//load and set ca
			TCHAR szPath[256] = {0};
			::GetModuleFileName(NULL, szPath, 255);
			(_tcsrchr(szPath, _T('\\')))[1] = 0; 

			CString strFile(szPath);
			strFile.Append(_T("ca.p12"));

			CFile file;
			if(!file.Open(strFile, CFile::modeRead)) 
			{	
				_tprintf(_T("Open ca file error %d\n"), ::GetLastError());
				goto END;
			}

			std::vector clientPfx(file.GetLength(), 0);
			file.Read(&clientPfx[0], file.GetLength());

			file.Close();

			// Convert a .pfx or .p12 file image to a Certificate store
			CRYPT_DATA_BLOB PFX;
			PFX.pbData= (BYTE *)&clientPfx[0];
			PFX.cbData= clientPfx.size();

			HCERTSTORE pfxStore= ::PFXImportCertStore( &PFX, pszPassWord, 0 );
			if ( NULL == pfxStore )
			{
				_tprintf(_T("PFXImportCertStore error %d\n"), ::GetLastError());
				goto END;
			}

			// Extract the certificate from the store and pass it to WinHttp
			PCCERT_CONTEXT pcontext= NULL, clientCertContext = NULL;
			while ( pcontext = ::CertEnumCertificatesInStore( pfxStore, pcontext ) ){
				clientCertContext= ::CertDuplicateCertificateContext( pcontext ); // CertEnumCertificatesInStore frees its passed in pcontext !

				BOOL stat= ::WinHttpSetOption( hRequest, WINHTTP_OPTION_CLIENT_CERT_CONTEXT, (LPVOID)clientCertContext, sizeof(CERT_CONTEXT) );	
				if ( FALSE == stat ) 
				{
                    _tprintf(_T("WinHttpSetOption error %d\n"), ::GetLastError());

					CertCloseStore(pfxStore,0);
			        CertFreeCertificateContext(clientCertContext);

				    goto END;
				}
				else
				{
					break;//success
				}
			}

			CertCloseStore(pfxStore,0);
			CertFreeCertificateContext(clientCertContext);

			// Certain circumstances dictate that we may need to loop on WinHttpSendRequest
			// hence the do/while
			bool retry = false;
			int result = NO_ERROR;
			do
			{
				retry = false;
				result = NO_ERROR;

				// no retry on success, possible retry on failure
				if(WinHttpSendRequest(
					hRequest,
					WINHTTP_NO_ADDITIONAL_HEADERS,
					0,
					0,
					0,
					0,
					NULL
					) == FALSE)
				{
					result = GetLastError();

					// (1) If you want to allow SSL certificate errors and continue
					// with the connection, you must allow and initial failure and then
					// reset the security flags. From: "HOWTO: Handle Invalid Certificate
					// Authority Error with WinInet"
					// http://support.microsoft.com/default.aspx?scid=kb;EN-US;182888
					if(result == ERROR_WINHTTP_SECURE_FAILURE)
					{
						DWORD dwFlags =
							SECURITY_FLAG_IGNORE_UNKNOWN_CA |
							SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE |
							SECURITY_FLAG_IGNORE_CERT_CN_INVALID |
							SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;

						if(WinHttpSetOption(
							hRequest,
							WINHTTP_OPTION_SECURITY_FLAGS,
							&dwFlags,
							sizeof(dwFlags)))
						{
							retry = true;
						}
					}
					// (2) Negotiate authorization handshakes may return this error
					// and require multiple attempts
					// http://msdn.microsoft.com/en-us/library/windows/desktop/aa383144%28v=vs.85%29.aspx
					else if(result == ERROR_WINHTTP_RESEND_REQUEST)
					{
						retry = true;
					}
				}
				else
				{
					bResults = TRUE;
				}
			} while(retry);
		}


		// End the request.
		if( bResults )
			bResults = WinHttpReceiveResponse( hRequest, NULL );

		// Keep checking for data until there is nothing left.
		if( bResults )
		{
			do 
			{
				// Check for available data.
				dwSize = 0;
				if( !WinHttpQueryDataAvailable( hRequest, &dwSize ) )
				{
					TRACE( "Error %u in WinHttpQueryDataAvailable.\n",
					GetLastError( ) );
				}

				// Allocate space for the buffer.
				pszOutBuffer = new char[dwSize+1];
				if( !pszOutBuffer )
				{
					TRACE( "Out of memory\n" );
					dwSize=0;
				}
				else
				{
					// Read the data.
					ZeroMemory( pszOutBuffer, dwSize+1 );

					if( !WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, 
						dwSize, &dwDownloaded ) )
						TRACE( "Error %u in WinHttpReadData.\n", GetLastError( ) );
					else
						TRACE( "%s", pszOutBuffer );

					// Free the memory allocated to the buffer.
					delete [] pszOutBuffer;
				}
			} while( dwSize > 0 );
		}


		// Report any errors.
		if( !bResults )
			TRACE( "Error %d has occurred.\n", GetLastError( ) );

		WinHttpSetStatusCallback( hSession,
			NULL,
			WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS,
			NULL );
END:
		// Close any open handles.
		if( hRequest ) WinHttpCloseHandle( hRequest );
		if( hConnect ) WinHttpCloseHandle( hConnect );
		if( hSession ) WinHttpCloseHandle( hSession );


你可能感兴趣的:(ssl,windows,openssl)