c++ winhttp通过https双向认证

2024-01-18 23:08
文章标签 c++ 认证 https 双向 winhttp

本文主要是介绍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<unsigned char> 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 caTCHAR 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<unsigned char> clientPfx(file.GetLength(), 0);file.Read(&clientPfx[0], file.GetLength());file.Close();// Convert a .pfx or .p12 file image to a Certificate storeCRYPT_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 WinHttpPCCERT_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/whilebool retry = false;int result = NO_ERROR;do{retry = false;result = NO_ERROR;// no retry on success, possible retry on failureif(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;182888if(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.aspxelse 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( ) );elseTRACE( "%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 );


这篇关于c++ winhttp通过https双向认证的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/620554

相关文章

利用c++判断水仙花数并输出示例代码

《利用c++判断水仙花数并输出示例代码》水仙花数是指一个三位数,其各位数字的立方和恰好等于该数本身,:本文主要介绍利用c++判断水仙花数并输出的相关资料,文中通过代码介绍的非常详细,需要的朋友可以... 以下是使用C++实现的相同逻辑代码:#include <IOStream>#include <vec

基于C++的UDP网络通信系统设计与实现详解

《基于C++的UDP网络通信系统设计与实现详解》在网络编程领域,UDP作为一种无连接的传输层协议,以其高效、低延迟的特性在实时性要求高的应用场景中占据重要地位,下面我们就来看看如何从零开始构建一个完整... 目录前言一、UDP服务器UdpServer.hpp1.1 基本框架设计1.2 初始化函数Init详解

C++ 右值引用(rvalue references)与移动语义(move semantics)深度解析

《C++右值引用(rvaluereferences)与移动语义(movesemantics)深度解析》文章主要介绍了C++右值引用和移动语义的设计动机、基本概念、实现方式以及在实际编程中的应用,... 目录一、右值引用(rvalue references)与移动语义(move semantics)设计动机1

Nginx之https证书配置实现

《Nginx之https证书配置实现》本文主要介绍了Nginx之https证书配置的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起... 目录背景介绍为什么不能部署在 IIS 或 NAT 设备上?具体实现证书获取nginx配置扩展结果验证

C++ move 的作用详解及陷阱最佳实践

《C++move的作用详解及陷阱最佳实践》文章详细介绍了C++中的`std::move`函数的作用,包括为什么需要它、它的本质、典型使用场景、以及一些常见陷阱和最佳实践,感兴趣的朋友跟随小编一起看... 目录C++ move 的作用详解一、一句话总结二、为什么需要 move?C++98/03 的痛点⚡C++

详解C++ 存储二进制数据容器的几种方法

《详解C++存储二进制数据容器的几种方法》本文主要介绍了详解C++存储二进制数据容器,包括std::vector、std::array、std::string、std::bitset和std::ve... 目录1.std::vector<uint8_t>(最常用)特点:适用场景:示例:2.std::arra

C++构造函数中explicit详解

《C++构造函数中explicit详解》explicit关键字用于修饰单参数构造函数或可以看作单参数的构造函数,阻止编译器进行隐式类型转换或拷贝初始化,本文就来介绍explicit的使用,感兴趣的可以... 目录1. 什么是explicit2. 隐式转换的问题3.explicit的使用示例基本用法多参数构造

C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解

《C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解》:本文主要介绍C++,C#,Rust,Go,Java,Python,JavaScript性能对比全面... 目录编程语言性能对比、核心优势与最佳使用场景性能对比表格C++C#RustGoJavapythonjav

C++打印 vector的几种方法小结

《C++打印vector的几种方法小结》本文介绍了C++中遍历vector的几种方法,包括使用迭代器、auto关键字、typedef、计数器以及C++11引入的范围基础循环,具有一定的参考价值,感兴... 目录1. 使用迭代器2. 使用 auto (C++11) / typedef / type alias

C++ scoped_ptr 和 unique_ptr对比分析

《C++scoped_ptr和unique_ptr对比分析》本文介绍了C++中的`scoped_ptr`和`unique_ptr`,详细比较了它们的特性、使用场景以及现代C++推荐的使用`uni... 目录1. scoped_ptr基本特性主要特点2. unique_ptr基本用法3. 主要区别对比4. u