0

I need to generate a SHA-1 code from a file content (so for example the same image with different names produces the same code). I would prefer to use openssl, since it seems to be the more performant.

In this question is explained how to obtain a SHA-1 from a file content, but it doesn't gurantee to work for certain files.

There is any solution for this problem (even using other library than openssl, but again performance are really important).

Community
  • 1
  • 1
justHelloWorld
  • 6,478
  • 8
  • 58
  • 138

1 Answers1

1

This example illustrates how to generate a SHA1 digest from a file and display it in its hexadecimal representation using openssl:

#include <stdio.h>
#include <openssl/sha.h>

#define MAX_BUF_LEN ( 1024 * 8 )

int sha1( const char * name, unsigned char * out )
{
    FILE * pf;
    unsigned char buf[ MAX_BUF_LEN ];
    SHA_CTX ctxt;

    pf = fopen( name, "rb" );

    if( !pf )
        return -1;

    SHA1_Init( &ctxt );

    while(1)
    {
        size_t len;

        len = fread( buf, 1, MAX_BUF_LEN, pf );

        if( len <= 0 )
            break;

        SHA1_Update( &ctxt, buf, len );
    }

    fclose(pf);

    SHA1_Final( out, &ctxt );

    return 0;
}


void bin2hex( unsigned char * src, int len, char * hex )
{
    int i, j;

    for( i = 0, j = 0; i < len; i++, j+=2 )
        sprintf( &hex[j], "%02x", src[i] );
}


int main( int argc, char * argv[] )
{
    unsigned char digest[ SHA_DIGEST_LENGTH ];
    char str[ (SHA_DIGEST_LENGTH * 2) + 1 ];

    if( sha1( argv[1], digest ) )
    {
        printf("Error!\n");
        return 1;
    }

    bin2hex( digest, sizeof(digest), str );

    printf("SHA1: %s\n", str );

    return 0;
}

/* eof */

Compiling:

$ gcc sha1.c -lcrypto -o sha1

Testing:

$ cat file.txt 
The quick brown fox jumps over the lazy dog

$ ./sha1 file.txt
SHA1: be417768b5c3c5c1d9bcb2e7c119196dd76b5570

$ sha1sum file.txt 
be417768b5c3c5c1d9bcb2e7c119196dd76b5570  file.txt

Voilá! There is no mystery!

Lacobus
  • 1,590
  • 12
  • 20