c++ - 您如何使用 WinHTTP 通过自签名证书执行 SSL

标签 c++ c winapi ssl winhttp

我似乎对此有疑问,并且本着有一个可以被其他人引用的通用问题的精神,我正在寻找一个使用 SSL 的好例子。

更具体地说,我从 WinHttpSendRequest 收到错误 0x00002F8F,即 ERROR_INTERNET_DECODING_FAILED(向我表明这是一个证书错误)。我已经在这台机器上导入了证书,并且能够在没有证书错误的情况下在 IE 中调出页面。

The code I am using is here.

TLDR:如何使用带有自签名证书的 WinHTTP?

最佳答案

对于 WinHTTP,为了接受/允许 SSL 验证失败,您必须首先发出请求并允许它失败,然后禁用安全检查并重试请求句柄上的操作。类似的东西:

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

    // no retry on success, possible retry on failure
    if(WinHttpSendRequest(
        mHRequest,
        WINHTTP_NO_ADDITIONAL_HEADERS,
        0,
        optionalData,
        optionalLength,
        totalLength,
        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(
                mHRequest,
                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;
        }
    }
} while(retry);

关于c++ - 您如何使用 WinHTTP 通过自签名证书执行 SSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19338395/

相关文章:

c++ - 调整 cv::Mat 大小的最有效方法

c - 队列陷入循环

c - 我的程序没有 printf 就无法运行

c - cisco路由器中使用C的USB调制解调器设备软件

windows - LogicalBytesPerSector 与 PhysicalBytesPerSector

c++ - 将构造对象但不是构造函数的方法

c++ - 给定种子和偏移量生成下一个伪随机值

c++ - winapi listview检查项c++

c++ - 当然有办法获得当前文件夹 View 的完整 View 下拉菜单吗?

C++:使用重载的复合赋值运算符时出现运行时错误