Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MD5 routines that are GLib friendly?

Tags:

c

linux

glib

Does anyone know of an MD5/SHA1/etc routine that is easily used with GLib (i.e. you can give it a GIOChannel, etc)?

like image 900
Ana Betts Avatar asked Sep 22 '08 01:09

Ana Betts


2 Answers

Unless you have a very good reason, use glib's built-in MD5, SHA1, and SHA256 implementations with GChecksum. It doesn't have a built-in function to construct a checksum from an IO stream, but you can write a simple one in 10 lines, and you'd need to write a complex one yourself anyway.

like image 81
John Millikin Avatar answered Oct 31 '22 18:10

John Millikin


You normally have to do library glue stuff yourself...

void get_channel_md5( GIOChannel* channel, unsigned char output[16] )
{
    md5_context ctx;

    gint64 fileSize = <get file size somehow?>;
    gint64 filePos = 0ll;

    gsize bufferSize = g_io_channel_get_buffer_size( channel );
    void* buffer = malloc( bufferSize );

    md5_starts( &ctx );

    // hash buffer at a time: 
    while ( filePos < fileSize )
    {
        gint64 size = fileSize - filePos;
        if ( size > bufferSize )
            size = bufferSize;

        g_io_channel_read( channel, buffer );
        md5_update( &ctx, buffer, (int)size );

        filePos += bufferSize;
    }

    free( buffer );

    md5_finish( &ctx, output );
}
like image 2
Simon Buchan Avatar answered Oct 31 '22 17:10

Simon Buchan