在C++中,使用WinHttp庫進行HTTP請求時,可能需要對服務器的SSL/TLS證書進行驗證
以下是一個示例代碼,展示了如何在C++中使用WinHttp庫進行安全證書驗證設置:
#include<Windows.h>
#include <WinHttp.h>
#include<iostream>
int main() {
// 初始化WinHttp
HINTERNET hSession = WinHttpOpen(L"MyUserAgent", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSession) {
std::cerr << "WinHttpOpen failed: "<< GetLastError()<< std::endl;
return 1;
}
// 連接到服務器
HINTERNET hConnect = WinHttpConnect(hSession, L"example.com", INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!hConnect) {
std::cerr << "WinHttpConnect failed: "<< GetLastError()<< std::endl;
WinHttpCloseHandle(hSession);
return 1;
}
// 創建請求
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if (!hRequest) {
std::cerr << "WinHttpOpenRequest failed: "<< GetLastError()<< std::endl;
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
// 設置安全證書驗證選項
DWORD dwOption = SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE;
if (!WinHttpSetOption(hRequest, WINHTTP_OPTION_SECURITY_FLAGS, &dwOption, sizeof(dwOption))) {
std::cerr << "WinHttpSetOption failed: "<< GetLastError()<< std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
// 發送請求
if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0)) {
std::cerr << "WinHttpSendRequest failed: "<< GetLastError()<< std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
// 接收響應
if (!WinHttpReceiveResponse(hRequest, NULL)) {
std::cerr << "WinHttpReceiveResponse failed: "<< GetLastError()<< std::endl;
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
// 處理響應
// ...
// 清理資源
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 0;
}
在這個示例中,我們設置了WINHTTP_OPTION_SECURITY_FLAGS
選項,忽略了未知的CA、證書日期無效、證書CN無效和證書用途不正確的錯誤。這些選項可以根據實際需求進行調整。
請注意,這個示例僅用于演示目的,實際應用中應該根據需要進行適當的錯誤處理和資源管理。