Home    | Products    | Downloads    | Purchase    | Support   

 Products

 Paint Express

 HashCalc

 FSUM

 QuickHash Library

    Download

    Purchase

    Samples

    License Agreement

    Related Links

    F.A.Q.

    Overview

 FastCRC Library

 Company

 About Us

 Contact Us

 Miscellaneous

 Affiliate Program

 Site Map

SlavaSoft QuickHash Library Samples
Sample #12 (QuickHash API - C)  

All

Previous Next


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

#include <stdio.h>
#include <string.h>
#include <QuickHash.h>

#define BUFF_SIZE  1024

int CalculateFileHMAC_SHA256( const char* filename, const char* key, char* hmachex )
{
    FILE* file;
    unsigned char buff[ BUFF_SIZE ];
    unsigned char context[ SLC_HMAC_CONTEXTSIZE( SLC_SHA256_CONTEXTSIZE, SLC_SHA256_BLOCKSIZE ) ];

    file = fopen( filename, "rb" );

    if( file == NULL )
    {
        printf( "\nCould not open file: %s", filename );
        return 0;
    }

    /*****Initialize the context before calling Update, Final, or FinalHex****/

    SL_HMAC_Init( context, SLC_SHA256_ALGID, key, strlen( key ) );

    /*****Calculate the HMAC by calling Update for each block of the file*****/

    while( !feof( file ) )
    {
        unsigned int nCount = fread( buff, sizeof( char ), BUFF_SIZE, file );
        if( ferror( file ) )
        {
            printf( "\nAn error occurred when accessing the file: %s", filename );
            fclose( file );
            return 0;
        }
        SL_HMAC_Update( context, buff, nCount );
    }

    /*****Do final changes and get the HMAC in hex format*********************/

    SL_HMAC_FinalHex( context, hmachex, 0 ); /* SL_HMAC_FinalHex reinitializes the context */

    fclose( file );

    return 1;
}

int main()
{
    char buff[ 256 ];
    char key[ 256 ];

    char hmachex[ SLC_SHA256_HEXDIGESTSIZE ]; /*0 terminated*/

    do
    {
        /*****Get the file name and the key from the user*************************/

        printf( "\nEnter a file name:\n" );
        gets( buff );

        printf( "\nEnter a key:\n" );
        gets( key );

        /*****Calculate the HMAC**************************************************/

        if( CalculateFileHMAC_SHA256( buff, key, hmachex ) != 0 )
            printf( "\nSHA256 HMAC: %s", hmachex );

        /*****Continue?***********************************************************/

        printf( "\nContinue (Y/N)?" );
        gets( buff );

    } while ( *buff == 'y' || *buff == 'Y' );

    return 0;
}
 
  Copyright SlavaSoft Inc. All rights reserved.