Xceed Encryption Library Documentation
Hashing a file (VC++ streaming example)
Examples > Hashing a file (VC++ streaming example)
VC++ Copy Code

// This example hashes data using the SHA 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;  

  IXceedHashingPtr piHash; 

  piHash.CreateInstance( CLSID_XceedHashing ); 
  piHash->License( _bstr_t( L"your license key ) ); 

  IXceedSHAHashingMethodPtr piSHA; 

  piSHA.CreateInstance( CLSID_XceedSHAHashingMethod ); 
  piSHA->PutHashSize( 256 ); 

  piHash->HashingMethod = IXceedHashDataPtr( piSHA );  

  BYTE* pcHashValue = NULL; 
  short nHashValueSize; 
  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. 
    piHash->ReadFile( "c:\\temp\\source.txt", lOffset, CHUNKSIZE, efpHash, 
                      (lOffset + CHUNKSIZE >= lFileSize), &dwBytesRead );  

    lOffset += dwBytesRead; 
  }  

  piSHA->GetHashValue( &pcHashValue, &nHashValueSize );  

  //Do something with the HashValue...  

  MessageBox( NULL, "File hashed successfully to memory", "Hashing result", MB_OK );  

  CoTaskMemFree( pcHashValue ); 
}
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();