0

Im having the code below but no matter what i pass as key the CryptDecrypt always return 1/TRUE, I have problem checking if the provided key is correct or not.

void DecryptAES(char* content, DWORD contentlen, char* key, DWORD keyLen) {
    HCRYPTPROV hProv;
    HCRYPTHASH hHash;
    HCRYPTKEY hKey;

    if (!CryptAcquireContextW(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
        printf("Failed in CryptAcquireContextW (%u)\n", GetLastError());
        return;
    }
    if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)) {
        printf("Failed in CryptCreateHash (%u)\n", GetLastError());
        return;
    }
    if (!CryptHashData(hHash, (BYTE*)key, keyLen, 0)) {
        printf("Failed in CryptHashData (%u)\n", GetLastError());
        return;
    }
    if (!CryptDeriveKey(hProv, CALG_AES_256, hHash, 0, &hKey)) {
        printf("Failed in CryptDeriveKey (%u)\n", GetLastError());
        return;
    }

    if (!CryptDecrypt(hKey, (HCRYPTHASH)NULL, 0, 0, (BYTE*)content, &contentlen)) {
        printf("Failed in CryptDecrypt (%u)\n", GetLastError());
        return;
    }

    CryptReleaseContext(hProv, 0);
    CryptDestroyHash(hHash);
    CryptDestroyKey(hKey);

}

What is wrong with this code?

Thanks

Alex
  • 49
  • 6
  • 3
    You can't tell whether the key is correct. You can apply any key to the cyphertext, and get *some* plaintext - it's just that for any key other than the correct one, you get back random garbage. If you want integrity in addition to security, you need to arrange for that separately, e.g. by including the hash of the intended plaintext along with the encrypted data. See [HMAC](https://en.wikipedia.org/wiki/HMAC) – Igor Tandetnik Mar 14 '23 at 14:31
  • The actual decryption algorithm is successful, but the only real way to know if the key was correct is to analyze the decrypted data to make sure it is what you are expecting. – Remy Lebeau Mar 14 '23 at 14:32
  • 1
    I don't think `CryptDecrypt` checks that the key you pass it is the key used to encrypt the data, if that's what you're asking. You just won't get the original data back if it differs. – Paul Sanders Mar 14 '23 at 14:32
  • Note in particular that the error code `NTE_BAD_KEY` doesn't mean that the key were incorrect (`CryptDecrypt` has no way of knowing). It just means that what you passed as the `hKey` argument doesn't match the structural requirements. – IInspectable Mar 14 '23 at 14:39

0 Answers0