【问题标题】:CryptHashData returns ERROR_INVALID_PARAMETER (CAPI)CryptHashData 返回 ERROR_INVALID_PARAMETER (CAPI)
【发布时间】:2018-01-25 05:44:39
【问题描述】:

CryptHashData (https://msdn.microsoft.com/en-us/library/windows/desktop/aa380202(v=vs.85).aspx) 始终返回 FALSE。当我调用 GetLastError 时,我返回一个值 87,它是常量 ERROR_INVALID_PARAMETER。我已经验证了我的参数(MSDN 注释说要检查传入的指针),一切看起来都很好。我把它放在尽可能接近 MSDN 代码示例的地方。

我的目标只是散列密码并从中派生密钥。

我在 Windows 10 上运行此代码。

我的代码:

std::string sPassword = "123P@ssword"; //password to hash
HCRYPTHASH hHash = NULL; //password hash handle
HCRYPTPROV hHashKeyProvider = NULL; //provider to make the key derived from the hash
HCRYPTKEY hHashDerivedKey = NULL; //key derived from password hash

//get provider to the hash based password
if (!CryptAcquireContext(
    &hHashKeyProvider,
    0,
    MS_ENHANCED_PROV,
    PROV_RSA_FULL,
    CRYPT_VERIFYCONTEXT
))
{
    throw std::runtime_error("Could not acquire context to make key from hash");
}

//create hash object from provider
if (!CryptCreateHash(
    hHashKeyProvider,
    CALG_SHA1,
    0,
    0,
    &hHash
))
{
    CryptReleaseContext(hHashKeyProvider, 0);
    throw std::runtime_error("Could not create hash");
}

//get hash of password
//https://msdn.microsoft.com/en-us/library/windows/desktop/aa380202(v=vs.85).aspx
BYTE* pbPasswordBuffer = (BYTE*)sPassword.c_str();
DWORD dwPasswordBufferLength = strlen((char*)pbPasswordBuffer);
if (!CryptHashData(
    hHashKeyProvider,
    pbPasswordBuffer,
    dwPasswordBufferLength,
    0
))
{
    CryptReleaseContext(hHashKeyProvider, 0);
    DWORD dwLast = GetLastError(); //THIS EQUALS 87 for ERROR_INVALID_PARAMETER WHY???
    throw std::runtime_error("Could not hash password");
}

//create key from hash
if (!CryptDeriveKey(
    hHashKeyProvider,
    CALG_AES_256,
    hHash,
    0,
    &hHashDerivedKey
))
{
    CryptDestroyHash(hHash);
    CryptReleaseContext(hHashKeyProvider, 0);
    throw std::runtime_error("Could not create key from password hash");
}

//free the hash
CryptDestroyHash(hHash);

建议?

【问题讨论】:

    标签: c++ hash


    【解决方案1】:

    注意,您不小心将 hHashKeyProvider 而不是 hHash 传递到 CryptHashData()

    此外,您的GetLastError() 调用应位于CryptReleaseContext() 之前,否则后者中的错误可能看起来像是来自CryptHashData()

    【讨论】:

      【解决方案2】:
      if (!CryptHashData(
          hHashKeyProvider,
      

      应该是

      if (!CryptHashData(
          hHash,
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-03
        • 1970-01-01
        • 1970-01-01
        • 2015-04-04
        • 1970-01-01
        相关资源
        最近更新 更多