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);

有什么建议吗?

最佳答案

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

另外,您的GetLastError()调用应该在CryptReleaseContext()之前,否则后者中的错误似乎来自CryptHashData()

10-07 13:40