I am trying to make a simple application which encrypts a string and then decrypts it. So far my code:
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 );
}
}
This produces the output:
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
So basicly it is almost working, but at the and of the encrypted string there are characters left from the encrypted string.
So my question is, am i doing something wrong or am i just missing something?
Thanks in advance!