c – MS CryptoAPI在带有CryptAcquireContext()的Windows XP上不起作用

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

我将失败归结为CryptAcquireContext()调用.

我注意到a previous post谈到了“……(Prototype)”的XP错误命名,必须通过使用WinXP特定宏MS_ENH_RSA_AES_PROV_XP来解决.

我做了XP特定的代码修改,它仍然无法正常工作. (bResult在Win XP上返回0 false,所有其他平台bResult返回1为真.)

我检查了MS_ENH_RSA_AES_PROV_XP与我在regedit.exe中看到的实际键字符串值,所以一切看起来都设置为工作但没有成功.

我是否忽略了一些可以在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失败:

解决方法:

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

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

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

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

上一篇:2020最新 visual studio 2019 16.8.3 企业版 完整离线安装包


下一篇:java – 如何将大字符串转换为十六进制,然后转换为字节?