Crypto API Question
-
I am crazying with a problem with the following function:
CStringA EncryptDecryptString(CStringA szString, BOOL bEncrypt)
{
HCRYPTPROV hCryptProv = NULL;
LPCWSTR keyContainer = _T("MyKeyContainer");if(CryptAcquireContext(&hCryptProv,keyContainer,NULL,PROV\_RSA\_FULL,0)) if (GetLastError() == NTE\_BAD\_KEYSET) CryptAcquireContext(&hCryptProv,keyContainer,NULL,PROV\_RSA\_FULL,CRYPT\_NEWKEYSET); HCRYPTHASH hHash = NULL; TCHAR szPassword\[11\] = \_T("Password"); if(CryptCreateHash(hCryptProv,CALG\_MD5,0,0,&hHash)) { if(!CryptHashData(hHash,(BYTE \*)szPassword,wcslen(szPassword),0)) { // reset hash object to NULL CryptDestroyHash(hHash); hHash = NULL; } } HCRYPTKEY hKey = NULL; CryptDeriveKey(hCryptProv,CALG\_RC4,hHash,0x00800000,&hKey); DWORD length= szString.GetLength() + 1; BYTE \* cipherBlock= (BYTE \*)malloc(length); memset(cipherBlock, 0, length); memcpy(cipherBlock, szString, length -1); if (bEncrypt) CryptEncrypt(hKey,0,TRUE,0,cipherBlock,&length,length); else CryptDecrypt(hKey,0,TRUE,0,cipherBlock,&length); CStringA szOutString(cipherBlock); if(cipherBlock) free(cipherBlock); if(hKey) CryptDestroyKey(hKey); if(hHash) CryptDestroyHash(hHash); if(hCryptProv) CryptReleaseContext(hCryptProv,0); return szOutString;
}
It's all ok with function, but sometimes when string is very very long during the Decryption i have only a part of string becouse the allocated memeory is not enought. How can i alloc the correct amount of memory during the decryption phase?
-
I am crazying with a problem with the following function:
CStringA EncryptDecryptString(CStringA szString, BOOL bEncrypt)
{
HCRYPTPROV hCryptProv = NULL;
LPCWSTR keyContainer = _T("MyKeyContainer");if(CryptAcquireContext(&hCryptProv,keyContainer,NULL,PROV\_RSA\_FULL,0)) if (GetLastError() == NTE\_BAD\_KEYSET) CryptAcquireContext(&hCryptProv,keyContainer,NULL,PROV\_RSA\_FULL,CRYPT\_NEWKEYSET); HCRYPTHASH hHash = NULL; TCHAR szPassword\[11\] = \_T("Password"); if(CryptCreateHash(hCryptProv,CALG\_MD5,0,0,&hHash)) { if(!CryptHashData(hHash,(BYTE \*)szPassword,wcslen(szPassword),0)) { // reset hash object to NULL CryptDestroyHash(hHash); hHash = NULL; } } HCRYPTKEY hKey = NULL; CryptDeriveKey(hCryptProv,CALG\_RC4,hHash,0x00800000,&hKey); DWORD length= szString.GetLength() + 1; BYTE \* cipherBlock= (BYTE \*)malloc(length); memset(cipherBlock, 0, length); memcpy(cipherBlock, szString, length -1); if (bEncrypt) CryptEncrypt(hKey,0,TRUE,0,cipherBlock,&length,length); else CryptDecrypt(hKey,0,TRUE,0,cipherBlock,&length); CStringA szOutString(cipherBlock); if(cipherBlock) free(cipherBlock); if(hKey) CryptDestroyKey(hKey); if(hHash) CryptDestroyHash(hHash); if(hCryptProv) CryptReleaseContext(hCryptProv,0); return szOutString;
}
It's all ok with function, but sometimes when string is very very long during the Decryption i have only a part of string becouse the allocated memeory is not enought. How can i alloc the correct amount of memory during the decryption phase?