I'm writting little program that will generate RSA key pair, export\import keys and encrypt string. So, I have written this code:
void EncryptString(std::string data)
{
int lenght = strlen(data.c_str());
DWORD temp = data.length() * sizeof(char);
DWORD possiblersa = 0;
unsigned char* buffer = new unsigned char[lenght];
std::copy(data.begin(), data.end(), buffer);
if (!CryptEncrypt(hKey, NULL, true, NULL, NULL, &possiblersa, NULL))
{
printf("Error: %d\n", GetLastError());
ExitThread(0);
}
if (!CryptEncrypt(hKey, NULL, true, NULL, buffer, &temp, possiblersa)) // Problem here
{
printf("Error: %d\n", GetLastError());
ExitThread(0);
}
DWORD dlen = 0;
if (!CryptBinaryToString(buffer, possiblersa, CRYPT_STRING_BASE64, NULL, &dlen))
{
printf("Error: %d\n", GetLastError());
ExitThread(0);
}
TCHAR* str = new TCHAR[dlen];
if (!CryptBinaryToString(buffer, possiblersa, CRYPT_STRING_BASE64, str, &dlen))
{
printf("Error: %d\n", GetLastError());
ExitThread(0);
}
for (DWORD i = 0; i < dlen; i++)
{
printf("%d\n", str);
}
delete[] buffer;
delete[] str;
}
CryptEncrypt ends with the crash. I don't know what should I do to fix this issue.
CryptEncrypt(hKey, NULL, true, NULL, NULL, &possiblersa, NULL))
will store in possiblersa
the amount of data that will be returned by encrypting zero bytes from the null pointer. You almost certainly need to pass in the actual data you want to encrypt (from data.c_str()
).
CryptEncrypt(hKey, NULL, true, NULL, buffer, &temp, possiblersa)
This encrypts your plaintext and claims that the buffer you have provided is of length possiblersa
. That is almost certainly not true: it is very likely to be the case that possiblersa
is much larger than length
.
You need to delay allocating the buffer (and copying the plaintext into it) until you have found how large the ciphertext buffer needs to be. (It will be at least as long as the plaintext, but it can be much longer.)