#include #include #include #include #include #include #include "md5.h" //buffer maximum #define MAX_BUF 2048 //lire le fichier char *readFile( const char *path); //generer le hash et imprimer dans CHECKSUM.MD5 bool hash_md5_file(const char *file); //strcpy prudent char *strCopy( char * str ); int main(int argc, char *argv[]) { if(!hash_md5_file("test2.xls")){ perror("fichier:"); }else{ puts("Hashage...OK"); } #ifdef WIN32 _getch(); #endif return 0; } char * readFile(const char *path) { FILE * pFile; long lSize; char * buffer; size_t result; pFile = fopen (path , "rb" ); if (pFile==NULL) {fputs ("File error",stderr); exit (1);} // obtain file size: fseek (pFile , 0 , SEEK_END); lSize = ftell (pFile); rewind (pFile); // allocate memory to contain the whole file: buffer = (char*) malloc (sizeof(char)*lSize); if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);} // copy the file into the buffer: result = fread (buffer,1,lSize,pFile); if (result != lSize) {fputs ("Reading error",stderr); exit (3);} // terminate fclose (pFile); return buffer; } bool hash_md5_file(const char *file) { /* ****Lire le fichier ***retourner un pointeur qui contient les donnees ***md5 hashage ***save le hex dans le fichier CHECKSUM.MD5 */ FILE *out; char *data; char output[]="CHECKSUM.MD5"; static char HEX_DATA[32]; md5_state_t state; md5_byte_t digest[16]; if(file==NULL){ return false; } data=readFile(file); //malloc and memset sont effectuer dans ===>readFile() if(data==NULL){ return false; } //MD5 HASH ALGORITHM md5_init(&state); md5_append(&state,(const md5_byte_t *)data,strlen(data)); md5_finish(&state,digest); int i=0; for(i;i<16;i++){ snprintf(HEX_DATA+i*2,sizeof(HEX_DATA),"%02x",digest[i]); } out=fopen(output,"a+"); if(out==NULL){ return false; } //fprintf(out,"MD5 (%s)= ",file); fprintf(out,"%s\n",HEX_DATA); printf("%s\n",HEX_DATA); //clean && close fflush(out); fclose(out); return true; } char *strCopy( char * str ) { if( !str ) { return NULL; } char *n = ( char * )malloc( strlen( str ) + 1 ); memcpy( n, str, strlen( str ) + 1 ); return n; }