如何正确加密数据?

时间:2014-10-30 21:23:58

标签: c++ windows cryptography

我有以下代码。我还想在此代码中添加一个密钥BYTE[]和一个IV BYTE[]来加密我的数据。为此,我必须致电CryptImportKeyCryptSetKeyParam

所以我的问题是:
我在哪里可以打电话给两个API?我想在CryptDeriveKey之后,然后使用CryptImportKey的输出来加密我的数据。我是对的吗? 我可以以某种方式确保结果加密正确吗?我是否应该进行一些其他更改以使我的代码更安全?

#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);
}

提前致谢!

0 个答案:

没有答案