程序挂起在对Wincrypt函数的函数调用中

Program hangs in a function call to Wincrypt functions

本文关键字:函数调用 函数 Wincrypt 挂起 程序      更新时间:2023-10-16

你能帮我处理这个代码吗?调用函数AesDecrypt时挂起。

#include <iostream>
#include <Windows.h>
#include <wincrypt.h>

struct AesKey {
    BLOBHEADER Header;
    DWORD dwKeyLength;
    BYTE cbKey[16];
        AesKey() {
          ZeroMemory(this, sizeof(*this));
          Header.bType = PLAINTEXTKEYBLOB;
          Header.bVersion = CUR_BLOB_VERSION;
          Header.reserved = 0;
          Header.aiKeyAlg = CALG_AES_128;
          dwKeyLength = 16;
        }
};
void AesDecrypt(unsigned char *output, unsigned char *input, int inLen, unsigned char *key, unsigned char *iv, int &plainSize) {
    HCRYPTPROV provider;
    AesKey rawKey;
    HCRYPTKEY cKey;
    BOOL hr = CryptAcquireContext(&provider, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0);
    if (hr == FALSE)
        throw "Unable to acquire AES Context";
    for (int i = 0; i < 16; i++)
        rawKey.cbKey[i] = key[i];
    hr = CryptImportKey(provider, (BYTE *) &rawKey, sizeof(AesKey), NULL, 0, &cKey);
    if (hr == FALSE)
        throw "Unable to import given key";
    hr = CryptSetKeyParam(cKey, KP_IV, (BYTE *) iv, 0);
    if (hr == FALSE)
        throw "Unable to set IV";
    DWORD dwMode = CRYPT_MODE_CBC;
    hr = CryptSetKeyParam(cKey, KP_MODE, (BYTE*) &dwMode, 0);
    if (hr == FALSE)
        throw "Unable to set mode";
    memcpy(output, input, inLen);
    DWORD d = (DWORD) inLen;
    hr = CryptDecrypt(cKey, NULL, TRUE, 0, output, &d);
    if (hr == FALSE)
    {
        int err = GetLastError();
        throw "Error during Decryption";
    }
    plainSize = d;
}
// codigo generado por mi
int main(int argc, char** argv) {
        unsigned char input[] = "SE83loTjmMeaG9+xoIyjng==";
        unsigned char *pinput = input;
        unsigned char output[] = "SE83loTjmMeaG9+xoIyjng==";
        unsigned char *poutput = output;
        unsigned char iv[]  = "1234567890ABCDEF";
        unsigned char *piv = iv;
        unsigned char key[] = "1234567890ABCDEF";
        unsigned char *pkey = key;
        int plaInt;
        AesDecrypt(poutput, pinput, 24, pkey, piv, plaInt);
        std::cout << output << std::endl;
        return 0;
}

调用函数时代码崩溃,我认为我传递指针是做错了什么。

抛出"char const*"实例后调用terminate

此应用程序已请求运行时在不同寻常的方式。请联系应用程序的支持团队以了解更多信息信息

--------------------------------进程已退出,返回值为255按任意键继续。

我怀疑这一行是罪魁祸首。

hr = CryptImportKey(provider, (BYTE *) &rawKey, sizeof(AesKey), NULL, 0, &cKey);

你可能打算使用

hr = CryptImportKey(provider, rawKey.cbKey, sizeof(AesKey), NULL, 0, &cKey);