问题描述:

I have the following code. I'd like to add to this code a key BYTE[] and an IV BYTE[] too, to encrypt my data with. To do that i have to call CryptImportKey and CryptSetKeyParam.

So my questions are:

Where do i have to call theese two APIs? I think after CryptDeriveKey, and then use the output from CryptImportKey to encrypt my data. Am i right?

Can i somehow ensure that the result is correct encrypted? Should i make some other changes to make my code more secure?

#include <string>

#include <iostream>

using namespace std;

struct CryptStuff

{

HCRYPTPROV* hProv;

HCRYPTKEY* hKey;

HCRYPTHASH* hHash;

CryptStuff(HCRYPTPROV* hprov, HCRYPTKEY* hkey, HCRYPTHASH* hash) :

hProv(hprov), hKey(hkey), hHash(hash) {}

~CryptStuff()

{

if ( *hKey ) CryptDestroyKey( *hKey );

if ( *hHash ) CryptDestroyHash( *hHash );

if ( *hProv ) CryptReleaseContext( *hProv, 0 );

}

};

void EncryptData( TCHAR *lpszPassword, char *pbBuffer, DWORD *dwCount )

{

HCRYPTPROV hProv = 0;

HCRYPTKEY hKey = 0;

HCRYPTHASH hHash = 0;

// create an instance of CryptStuff. This will cleanup the data on return

CryptStuff cs(&hProv, &hKey, &hHash);

LPWSTR wszPassword = lpszPassword;

DWORD cbPassword = ( wcslen( wszPassword ) + 1 )*sizeof( WCHAR );

if ( !CryptAcquireContext( &hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES,

CRYPT_VERIFYCONTEXT ) )

{

return;

}

if ( !CryptCreateHash( hProv, CALG_SHA_256, 0, 0, &hHash ) )

{

return;

}

if ( !CryptHashData( hHash, ( PBYTE )wszPassword, cbPassword, 0 ) )

{

return;

}

if ( !CryptDeriveKey( hProv, CALG_AES_256, hHash, CRYPT_EXPORTABLE, &hKey ) )

{

return;

}

DWORD size = ( DWORD )strlen( pbBuffer ) / sizeof( char );

cout << "\nLength of string = " << size;

if ( !CryptEncrypt( hKey, 0, TRUE, 0, ( LPBYTE )pbBuffer, &size, BLOCK_SIZE ) )

{

return;

}

cout << "\nEncrypted bytes = " << size;

cout << "\nEncrypted text = ";

cout.write(pbBuffer, size);

if ( !CryptDecrypt( hKey, 0, TRUE, 0, ( LPBYTE )pbBuffer, &size ) )

{

return;

}

cout << "\nDecrypted bytes = " << size;

cout << "\nDecrypted text = ";

cout.write(pbBuffer, size);

}

Thanks in advance!

相关阅读:
Top