tags:

views:

178

answers:

2

Simply what the topic states, what's a memory efficient way to compute a sha256 hash of a file that's variable in size? I'm also willing to compromise using more memory for faster computation.

+3  A: 

Or use the OpenSSL libcrypto:

http://www.openssl.org/docs/crypto/sha.html#

Wade Williams
(+1) but libssl takes some getting used to, the documentation is not easy to get into
Hassan Syed
+1 OpenSSL is FIPS-certified. It may take some effort to learn to use it, but far *less* effort than coding a correct SHA-256 implementation.
Bill Karwin
Is it possible to show a code sample using libcrypto?
randombits
There is a complete example at http://www.openssl.org/docs/crypto/EVP_DigestInit.html. You can replace the line md = EVP_get_digestbyname(argv[1]); with md = EVP_sha256();
GregS
+1  A: 

I used a simple stand-alone implementation by Christophe Devine -- and while his site seems to be off the Net, Google Code Search finds it in these places

Using these sha256.c and sha256.h, the core of his main() function is simply

if( ! ( f = fopen( argv[1], "rb" ) ) )
        {
            perror( "fopen" );
            return( 1 );
        }

        sha256_starts( &ctx );

        while( ( i = fread( buf, 1, sizeof( buf ), f ) ) > 0 )
        {
            sha256_update( &ctx, buf, i );
        }

        sha256_finish( &ctx, sha256sum );

        for( j = 0; j < 32; j++ )
        {
            printf( "%02x", sha256sum[j] );
        }

        printf( "  %s\n", argv[1] );
}

The rest of the main() function validates the FIPS-180-2 test vectors, so you get that warm and fuzzy feeling too/ ;-)

Dirk Eddelbuettel