我想做一個簡單的應用程序加密一個字符串,然後解密它。 到目前爲止我的代碼:CryptDecrypt在解碼字符串的末尾返回隨機字符?
int main(int argc, char* argv[])
{
char test[ 32 ] = { 0 };
strcpy(test, "This is a sample string.");
BYTE buf = NULL;
DWORD len = strlen(test);
EncryptData(lpszPassword, test, &len);
return 0;
}
void EncryptData(TCHAR *lpszPassword, char *pbBuffer, DWORD *dwCount)
{
HCRYPTPROV hProv = 0;
HCRYPTKEY hKey = 0;
HCRYPTHASH hHash = 0;
LPWSTR wszPassword = lpszPassword;
DWORD cbPassword = (wcslen(wszPassword) + 1)*sizeof(WCHAR);
if (!CryptAcquireContext(&hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
printf("Error %x during CryptAcquireContext!\n", GetLastError());
goto Cleanup;
}
if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash))
{
printf("Error %x during CryptCreateHash!\n", GetLastError());
goto Cleanup;
}
if (!CryptHashData(hHash, (PBYTE)wszPassword, cbPassword, 0))
{
printf("Error %x during CryptHashData!\n", GetLastError());
goto Cleanup;
}
if (!CryptDeriveKey(hProv, CALG_AES_256, hHash, CRYPT_EXPORTABLE, &hKey))//hKey
{
printf("Error %x during CryptDeriveKey!\n", GetLastError());
goto Cleanup;
}
DWORD size = (DWORD)strlen(pbBuffer)/sizeof(char);
printf("\nLength of string = %d", size);
if (!CryptEncrypt(hKey, 0, TRUE, 0, (LPBYTE)pbBuffer, &size, BLOCK_SIZE))
{
printf("Error %x during CryptEncrypt!\n", GetLastError());
goto Cleanup;
}
printf("\nEncrypted bytes = %d", size);
printf("\nEncrypted text = %s", pbBuffer);
if (!CryptDecrypt(hKey, 0, TRUE, 0, (LPBYTE)pbBuffer, &size))
{
printf("Error %x during CryptDecrypt!\n", GetLastError());
goto Cleanup;
}
printf("\nDecrypted bytes = %d", size);
printf("\nDecrypted text = %s", pbBuffer);
Cleanup:
if (hKey)
{
CryptDestroyKey(hKey);
}
if (hHash)
{
CryptDestroyHash(hHash);
}
if (hProv)
{
CryptReleaseContext(hProv, 0);
}
}
這將產生輸出:
Length of string = 24
Encrypted bytes = 32
Encrypted text = ╨é╖·ç┤╠├ó br.≡·►;╜K/┤E(↓)╫%┤Cà¡╩╠╠╠╠╘)Ñ°♀·L
Decrypted bytes = 24
Decrypted text = This is a sample string.)╫%┤Cà¡╩╠╠╠╠╘)Ñ°♀·L
所以basicly它幾乎工作,但是從加密的字符串留在加密的字符串的和有字符。
所以我的問題是,我做錯了什麼或者我只是想念什麼?
在此先感謝!
'Decrypted bytes = 24'指示緩衝區中有效數據的長度,但是您打印整個事物... – 2014-10-30 17:59:05
您將此標記爲'C++',但實際上它全部是'C'。 – PaulMcKenzie 2014-10-30 18:05:24
@PaulMcKenzie:對不起,錯打了它 – kampi 2014-10-30 18:07:53