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++右移运算符的一个小坑及解决》文章指出右移运算符处理负数时左侧补1导致死循环,与除法行为不同,强调需注意补码机制以正确统计二进制1的个数... 目录我遇到了这么一个www.chinasem.cn函数由此可以看到也很好理解总结我遇到了这么一个函数template<typename T>unsigned

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法

深入解析C++ 中std::map内存管理

《深入解析C++中std::map内存管理》文章详解C++std::map内存管理,指出clear()仅删除元素可能不释放底层内存,建议用swap()与空map交换以彻底释放,针对指针类型需手动de... 目录1️、基本清空std::map2️、使用 swap 彻底释放内存3️、map 中存储指针类型的对象

C++ STL-string类底层实现过程

《C++STL-string类底层实现过程》本文实现了一个简易的string类,涵盖动态数组存储、深拷贝机制、迭代器支持、容量调整、字符串修改、运算符重载等功能,模拟标准string核心特性,重点强... 目录实现框架一、默认成员函数1.默认构造函数2.构造函数3.拷贝构造函数(重点)4.赋值运算符重载函数

C++ vector越界问题的完整解决方案

《C++vector越界问题的完整解决方案》在C++开发中,std::vector作为最常用的动态数组容器,其便捷性与性能优势使其成为处理可变长度数据的首选,然而,数组越界访问始终是威胁程序稳定性的... 目录引言一、vector越界的底层原理与危害1.1 越界访问的本质原因1.2 越界访问的实际危害二、基

c++日志库log4cplus快速入门小结

《c++日志库log4cplus快速入门小结》文章浏览阅读1.1w次,点赞9次,收藏44次。本文介绍Log4cplus,一种适用于C++的线程安全日志记录API,提供灵活的日志管理和配置控制。文章涵盖... 目录简介日志等级配置文件使用关于初始化使用示例总结参考资料简介log4j 用于Java,log4c

C++归并排序代码实现示例代码

《C++归并排序代码实现示例代码》归并排序将待排序数组分成两个子数组,分别对这两个子数组进行排序,然后将排序好的子数组合并,得到排序后的数组,:本文主要介绍C++归并排序代码实现的相关资料,需要的... 目录1 算法核心思想2 代码实现3 算法时间复杂度1 算法核心思想归并排序是一种高效的排序方式,需要用

Linux中的HTTPS协议原理分析

《Linux中的HTTPS协议原理分析》文章解释了HTTPS的必要性:HTTP明文传输易被篡改和劫持,HTTPS通过非对称加密协商对称密钥、CA证书认证和混合加密机制,有效防范中间人攻击,保障通信安全... 目录一、什么是加密和解密?二、为什么需要加密?三、常见的加密方式3.1 对称加密3.2非对称加密四、

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符