【问题标题】:MS CryptoAPI doesn't work on Windows XP with CryptAcquireContext()MS CryptoAPI 在 Windows XP 上无法使用 CryptAcquireContext()
【发布时间】:2012-04-05 09:20:07
【问题描述】:

我使用 Microsoft CryptoAPI 编写了一些代码来计算 SHA-1,并让编译后的 exe 在 Windows 7、Win Server 2008、Win Server 2003 上运行。但是,当我在 Windows XP SP3 下运行它时,它不起作用.

我将失败范围缩小到CryptAcquireContext() 调用。

我确实注意到a previous post 谈到了“...(原型)”的 XP 错误命名,必须使用 WinXP 特定的宏 MS_ENH_RSA_AES_PROV_XP 来解决这个问题。

我对 XP 特定的代码进行了修改,但仍然无法正常工作。 (bResult 在 Win XP 上返回 0 false,所有其他平台 bResult 返回 1 true。)

我用我在 regedit.exe 中看到的实际键+字符串值检查了 MS_ENH_RSA_AES_PROV_XP,所以一切看起来都可以正常工作,但没有成功。

我是否忽略了一些使它在 Windows XP 上工作的东西?

我已粘贴最短的示例来说明问题。我用的是VS2010 C++。

// based on examples from http://msdn.microsoft.com/en-us/library/ms867086.aspx

#include "windows.h"
#include "wincrypt.h"
#include <iostream>
#include <iomanip>  // for setw()

void main()
{
    BOOL bResult;
    HCRYPTPROV hProv;

    // Attempt to acquire a handle to the default key container.
    bResult = CryptAcquireContext(
        &hProv,            // Variable to hold returned handle.
        NULL,              // Use default key container.
        MS_DEF_PROV,       // Use default CSP.
        PROV_RSA_FULL,     // Type of provider to acquire.
        0);                // No special action.
    std::cout << "line:  " << std::setw(4) << __LINE__ << ";  " << "bResult = " << bResult << std::endl;

    if (! bResult) {        // try Windows XP provider name
        bResult = CryptAcquireContext(
            &hProv,            // Variable to hold returned handle.
            NULL,              // Use default key container.
            MS_ENH_RSA_AES_PROV_XP,  // Windows XP specific instead of using default CSP.
            PROV_RSA_AES,     // Type of provider to acquire.
            0);                // No special action.
        std::cout << "line:  " << std::setw(4) << __LINE__ << ";  " << "bResult = " << bResult << std::endl;
    }

    if (bResult)
        CryptReleaseContext(hProv, 0);
}

Windows 7 成功:

Windows XP 故障:

【问题讨论】:

    标签: c++ visual-studio-2010 sha1 cryptoapi mscapi


    【解决方案1】:

    在您的 CryptAcquireContext 代码中,您似乎缺少获取没有特定容器集的上下文的参数。您需要在 CryptAcquireContext 中传递 CRYPT_VERIFYCONTEXT 选项。

    Windows 7 可能正在解决这个问题。

    http://msdn.microsoft.com/en-us/library/windows/desktop/aa379886(v=vs.85).aspx

    为了进一步诊断,GetLastError() 的结果是必需的。

    【讨论】:

    • 是的,成功了!谢谢你。我从中复制代码的 Microsoft 在线示例没有该参数。但更令人困惑的是,当我将 CRYPT_VERIFYCONTEXT 添加到第一个不使用 MS_ENH_RSA_AES_PROV_XP 的调用时,它也适用于 XP!奇怪,但我会接受的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 2016-12-02
    • 2013-06-30
    相关资源
    最近更新 更多