openssl编程之md5

 

/*
* md5.cc
* - Using md5 with openSSL. MD5 returns a 128-bit hash value from a string.
*   fangying 2012-4-3
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <io.h>
#include <openssl/md5.h>


long filesize(FILE *stream)
{
   long curpos, length;

   curpos = ftell(stream);
   fseek(stream, 0L, SEEK_END);
   length = ftell(stream);
   fseek(stream, curpos, SEEK_SET);
   return length;
}


int main() {
    FILE *fp;
    MD5_CTX hash_ctx;
    unsigned long flength = 0L;
    char filepath[128];
    char *str_file;
    unsigned char hash_ret[16];
    int i;

    printf("md5sum.exe version 1.0 create by fangying\n");
    printf("-------------------------------------------\n");
    printf("please input the file path : ");
    gets(filepath);
    printf("\nfilepath is : %s\n",filepath);
    //open the specified file

    if((fp = fopen(filepath,"rb")) == NULL){
        printf("Can't open file: %s \n",filepath);
        printf("Press any key to exit! \n");
        getchar();
        return 2;
    }
    // print
    printf("input file is : %s \n", filepath);

    //get file size
    flength = filesize(fp);
    printf("file size is: %ld byte(s) \n",flength);
    str_file = (char *)calloc(flength, sizeof(char));

    //read form the beginning
    rewind(fp);

    if ((fread(str_file, 1, flength, fp)) != flength)
    {
        printf("fread() length is : %ld \n",fread(str_file, flength, 1, fp));
        printf("fread() does't match flength\n");
    };


    // initialize a hash context
    MD5_Init(&hash_ctx);
    // update the input string to the hash context (you can update
    // more string to the hash context)
    MD5_Update(&hash_ctx, str_file, flength);

    // compute the hash result
    MD5_Final(hash_ret, &hash_ctx);


    printf("MD5 digest : ");
    for (i=0; i<32; ++i) {
        if (i % 2 == 0) {
            printf("%x", (hash_ret[i/2] >> 4) & 0xf);
        } else {
            printf("%x", (hash_ret[i/2]) & 0xf);
        }
    }
    printf("\npress any key to exit!");
    getchar();

    //free memory and close file
    free(str_file);
    fclose(fp);
    return 0;
}





 

 

posted @ 2012-06-02 16:04  fangying  阅读(868)  评论(0编辑  收藏  举报