I used to work with crypto++
in Visual Studio before, but now I want to use of wincrypt.h
API functions to encrypt a string with AES 256 with an IV (cbc mode).
I did bellow steps but I'm confused about CryptEncrypt()
and CryptDecrypt()
functions, because It seems they don't work properly :
CryptAcquireContextA
defined to create aCSP
:// create a cryptographic service provider (CSP) CryptAcquireContextA(&hProv, NULL, MS_ENH_RSA_AES_PROV_A, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)
For set key, I'm using of this way (import key):
CryptImportKey(hProv, (BYTE*)&AESBlob, sizeof(AES256KEYBLOB), NULL, CRYPT_EXPORTABLE, &hKey)
IV, Key, Plaintext sizes are :
#define DEFAULT_AES_KEY_SIZE 32 #define DEFAULT_IV_SIZE 16 #define BUFFER_FOR_PLAINTEXT 32
This is my whole code
:
// handles for csp and key
HCRYPTPROV hProv = NULL;
HCRYPTPROV hKey = NULL;
BYTE szKey[DEFAULT_AES_KEY_SIZE + 1] = {0};
BYTE szIV[DEFAULT_IV_SIZE + 1] = {0};
// plain bytes
BYTE szPlainText[BUFFER_FOR_PLAINTEXT + 1] = {0};
DWORD dwPlainSize = 0;
// initalize key and plaintext
StrCpyA((LPSTR)szKey, "00112233445566778899001122334455");
StrCpyA((LPSTR)szIV, "4455667788990011");
StrCpyA((LPSTR)szPlainText, "abcdefghijklmnopqrstuvwxyzabcdef");
// blob data for CryptImportKey() function (include key and version and so on...)
struct AES256KEYBLOB
{
AES256KEYBLOB() { StrCpyA((LPSTR)szBytes, 0); }
BLOBHEADER bhHdr;
DWORD dwKeySize;
BYTE szBytes[DEFAULT_AES_KEY_SIZE + 1];
} AESBlob;
AESBlob.bhHdr.bType = PLAINTEXTKEYBLOB;
AESBlob.bhHdr.bVersion = CUR_BLOB_VERSION;
AESBlob.bhHdr.reserved = 0;
AESBlob.bhHdr.aiKeyAlg = CALG_AES_256;
AESBlob.dwKeySize = DEFAULT_AES_KEY_SIZE;
StrCpyA((LPSTR)AESBlob.szBytes, (LPCSTR)szKey);
// create a cryptographic service provider (CSP)
if(CryptAcquireContextA(&hProv, NULL, MS_ENH_RSA_AES_PROV_A, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
if(CryptImportKey(hProv, (BYTE*)&AESBlob, sizeof(AES256KEYBLOB), NULL, CRYPT_EXPORTABLE, &hKey))
{
if(CryptSetKeyParam(hKey, KP_IV, szIV, 0))
{
if(CryptEncrypt(hKey, NULL, TRUE, 0, szPlainText, &dwPlainSize, lstrlenA((LPCSTR)szPlainText) + 1))
{
printf("\nEncrypted data : %s\nSize : %d\n", (LPCSTR)szPlainText, dwPlainSize);
if(CryptDecrypt(hKey, NULL, TRUE, 0, szPlainText, &dwPlainSize)) {
printf("\nDecrypted data : %s\nSize : %d\n", (LPCSTR)szPlainText, dwPlainSize);
}
else
printf("failed to decrypt!");
}
else
printf("failed to encrypt");
}
}
}
It just encrypt half section of plaintext And decrypting not done! even By changing just szPlainText
value, it always give me bellow output (It means that CryptEncrypt()
and CryptDecrypt()
does not working as expected!) :
Encrypted data : U╡π7ÑL|FΩ$}├rUqrstuvwxyzabcdef
Size : 16
Decrypted data : U╡π7ÑL|FΩ$}├rUqrstuvwxyzabcdef
Size : 0