QuickHash Library C++ Interface

The following sample demonstrates how to use the CHMAC class to calculate the HMAC for a file using SHA256 hash algorithm.

#include <fstream>
#include <iostream>
#include <QuickHash.h>

using namespace std;
using namespace QuickHash;

bool CalculateFileHMAC_SHA256( const char* filename, const char* key, char* hmachex )
{
    fstream file( filename, ios::in | ios::binary );
    
    if( !file )
    {
        cout << "\nCould not open file: " << filename;
        return false;
    }
    
    const unsigned int BUFF_SIZE = 1024;
    unsigned char buff[ BUFF_SIZE ];
    
    //Instantiate a CHMAC object
    
    CHMAC<CSHA256> hm( (const unsigned char*)key, strlen( key ) );
    
    //Calculate the HMAC by calling Update for each block of the file
    
    while( !file.eof() )
    {
        file.read( ( char* )buff, BUFF_SIZE );
        hm.Update( buff, file.gcount() );
    }
    
    //Do final changes and get the HMAC in hex format
    
    hm.FinalHex( hmachex ); // FinalHex reinitializes the hm object for the next use
    
    file.close();
    
    return true;
}

int main()
{
    char buff[ 10 ];

    char filename[ 256 ];
    char key[ 256 ];
    
    char hmachex[ CHMAC<CSHA256>::HEXDIGESTSIZE ]; //0 terminated
    
    do
    {
        //Get the file name and the key from the user
        
        cout << "\nEnter a file name:\n";
        cin.getline( filename, 256 );

        cout << "\nEnter the key:\n";
        cin.getline( key, 256 );
        
        //Calculate the HMAC using SHA256 hash algorithm
        
        if( CalculateFileHMAC_SHA256( filename, key, hmachex ) )
            cout << "\nSHA256 HMAC: " << hmachex;
        
        //Continue?
        
        cout << "\nContinue (Y/N)?";
        cin.getline( buff, 10 );
        
    } while ( *buff == 'y' || *buff == 'Y' );
    
    return 0;
}


 

 

Send Feedback to SlavaSoft Inc. Tell a friend about QuickHash Library