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++中初始化二维数组的不同方式,包括静态初始化、循环、全部为零、部分初始化、std::array和std::vector,以及std::vec... 目录1. 静态初始化2. 使用循环初始化3. 全部初始化为零4. 部分初始化5. 使用 std::a

SpringSecurity JWT基于令牌的无状态认证实现

《SpringSecurityJWT基于令牌的无状态认证实现》SpringSecurity中实现基于JWT的无状态认证是一种常见的做法,本文就来介绍一下SpringSecurityJWT基于令牌的无... 目录引言一、JWT基本原理与结构二、Spring Security JWT依赖配置三、JWT令牌生成与

C++ vector的常见用法超详细讲解

《C++vector的常见用法超详细讲解》:本文主要介绍C++vector的常见用法,包括C++中vector容器的定义、初始化方法、访问元素、常用函数及其时间复杂度,通过代码介绍的非常详细,... 目录1、vector的定义2、vector常用初始化方法1、使编程用花括号直接赋值2、使用圆括号赋值3、ve

如何高效移除C++关联容器中的元素

《如何高效移除C++关联容器中的元素》关联容器和顺序容器有着很大不同,关联容器中的元素是按照关键字来保存和访问的,而顺序容器中的元素是按它们在容器中的位置来顺序保存和访问的,本文介绍了如何高效移除C+... 目录一、简介二、移除给定位置的元素三、移除与特定键值等价的元素四、移除满足特android定条件的元

Python获取C++中返回的char*字段的两种思路

《Python获取C++中返回的char*字段的两种思路》有时候需要获取C++函数中返回来的不定长的char*字符串,本文小编为大家找到了两种解决问题的思路,感兴趣的小伙伴可以跟随小编一起学习一下... 有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:

C++ Sort函数使用场景分析

《C++Sort函数使用场景分析》sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变,如果某些场景需要保持相同元素间的相对顺序,可使... 目录C++ Sort函数详解一、sort函数调用的两种方式二、sort函数使用场景三、sort函数排序

SpringSecurity6.0 如何通过JWTtoken进行认证授权

《SpringSecurity6.0如何通过JWTtoken进行认证授权》:本文主要介绍SpringSecurity6.0通过JWTtoken进行认证授权的过程,本文给大家介绍的非常详细,感兴趣... 目录项目依赖认证UserDetailService生成JWT token权限控制小结之前写过一个文章,从S

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++

C/C++错误信息处理的常见方法及函数

《C/C++错误信息处理的常见方法及函数》C/C++是两种广泛使用的编程语言,特别是在系统编程、嵌入式开发以及高性能计算领域,:本文主要介绍C/C++错误信息处理的常见方法及函数,文中通过代码介绍... 目录前言1. errno 和 perror()示例:2. strerror()示例:3. perror(

C++变换迭代器使用方法小结

《C++变换迭代器使用方法小结》本文主要介绍了C++变换迭代器使用方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、源码2、代码解析代码解析:transform_iterator1. transform_iterat