我以前曾crypto++
在Visual Studio中使用过,但现在我想使用wincrypt.h
API 函数来使用带有IV(cbc 模式)的AES 256加密字符串。
我做了以下步骤,但我对功能感到困惑CryptEncrypt()
,CryptDecrypt()
因为它们似乎无法正常工作:
CryptAcquireContextA
定义为创建一个CSP
:// create a cryptographic service provider (CSP) CryptAcquireContextA(&hProv, NULL, MS_ENH_RSA_AES_PROV_A, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)
对于设置密钥,我使用这种方式(导入密钥):
CryptImportKey(hProv, (BYTE*)&AESBlob, sizeof(AES256KEYBLOB), NULL, CRYPT_EXPORTABLE, &hKey)
IV,密钥,明文大小为:
#define DEFAULT_AES_KEY_SIZE 32 #define DEFAULT_IV_SIZE 16 #define BUFFER_FOR_PLAINTEXT 32
这是我的全部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");
}
}
}
它只是加密了一半的明文而没有解密!即使只改变szPlainText
值,它也总是给我下面的输出(这意味着CryptEncrypt()
并且CryptDecrypt()
没有按预期工作!):
Encrypted data : U╡π7ÑL|FΩ$}├rUqrstuvwxyzabcdef
Size : 16
Decrypted data : U╡π7ÑL|FΩ$}├rUqrstuvwxyzabcdef
Size : 0