Xceed Encryption Library Documentation
Encrypting and decrypting from file to memory (VC++ streaming example)
Examples > Encrypting and decrypting from file to memory (VC++ streaming example)
VC++ Copy Code

// This example encrypt data using the Rijndael method from a file to memory in 8K (8192 byte) chunks. 

// This code uses the #import directive.

// Put the following line at the beginning of your module
#import "XCEEDCRY.DLL" no_namespace named_guids 

CoInitialize( NULL ); 

try
{
  const long CHUNKSIZE = 8192;  

  IXceedEncryptionPtr piEncrypt; 

  piEncrypt.CreateInstance( CLSID_XceedEncryption ); 
  piEncrypt->License( _bstr_t( L"your license key ) ); 

  IXceedRijndaelEncryptionMethodPtr piRijndael; 

  piRijndael.CreateInstance( CLSID_XceedRijndaelEncryptionMethod ); 
  piRijndael->SetSecretKeyFromPassPhrase( "This is a weak pass phrase!", 128 ); 

  piEncrypt->EncryptionMethod = IXceedEncryptDataPtr( piRijndael );  

  BYTE* pcData = NULL; 
  DWORD dwDataSize; 
  DWORD dwBytesRead; 
  long lOffset = 0;  

  HANDLE hFile = CreateFile( "c:\\temp\\source.txt", 0,
                             FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL );  

  if( hFile == INVALID_HANDLE_VALUE ) 
    throw;  

  long lFileSize = GetFileSize( hFile, NULL ); 
  CloseHandle( hFile );  

  if( lFileSize == 0xFFFFFFFF ) 
    throw;  

  while( lOffset < lFileSize ) 
  { 
    // bEndOfData will be true if the current offset + CHUNKSIZE exceeds the  end of the file. 

    piEncrypt->ReadFile( "c:\\temp\\source.txt", lOffset, CHUNKSIZE, efpEncrypt, 
                         (lOffset + CHUNKSIZE >= lFileSize), &dwBytesRead, &pcData, &dwDataSize );  

    lOffset += dwBytesRead;  

    if( dwDataSize > 0 ) 
    { 
      // You now have a portion of encrypted data you can use. 
      // For example, transfer it, process it, etc. 
      // Here, we just free it! 
      CoTaskMemFree( pcData ); 
    } 
  }  

  MessageBox( NULL, "File encrypted successfully to memory", "Encrypting result", MB_OK ); 
}
catch( const _com_error& xErr )
{
  char szMsg[50]; 
  wsprintf( szMsg, "Error %08x\n", xErr.Error() ); 
  MessageBox( NULL, szMsg, "Error", MB_OK ); 
}
catch( ... )
{
  MessageBox( NULL, "Unknown error", "Error", MB_OK ); 

CoUninitialize();