Question

I'm writing a native-C program which (among others) handles encryption/decryption of data. The data is processed (before or after execution) using a python script, whose main purpose is to encrypt/decrypt the data (and perhaps do some additional parsing of it).

I'm having problems in decrypting the data generated by WinCrypt API, using PyCrypto API, and vice-versa. Specifically I've experienced this problem in AES-256 based encryption. Both sides of the encryption/decryption scheme run on the same machine, and are provided the same encryption key. They are both CBC based and (if the documentation is not lying) are initialized with a 0-based initialization vector. However, no matter what I try to do, they don't seem to get along. The resulting data (encrypted using WinCrypt & decrypted using PyCrypto or vice versa) is all messed up (not even close to the original). Just to be clear - each of the mechanisms works on its own (decrypting WinCrypt-encrypted data using WinCrypt works perfectly, and the same for PyCrypto).

The native encryption code is based on WinCrypt's examples. It generally looks like the following code:

HCRYPTPROV hCryptProv;
HCRYPTKEY hKey;
HCRYPTHASH hHash;
CHAR szPassword[PASSWORD_LENGTH] = "";
DWORD dwLength;
PBYTE pbBuffer = NULL;   
DWORD dwBufferLen; 
DWORD dwCount; 

CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_AES, 0);
CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash);
CryptHashData(hHash, (BYTE *)szPassword, dwLength, 0);
CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey);

CryptEncrypt(hKey, NULL, FALSE, 0, pbBuffer, &dwCount, dwBufferLen);
CryptDecrypt(hKey, 0, FALSE, 0, pbBuffer, &dwCount);

(This is just a general scheme, and obviously the actual code contains all the necessary error handling, handles cleanup, etc).

The PyCrypto code:

from Crypto.Cipher import AES
context = AES.new("K"*32, mode=AES.MODE_CBC, IV="\x00"*16)
context.encrypt(ORIGINAL_DATA)
context.decrypt(ENC_DATA)

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top