純C/C++ MD5

純C/C++ MD5

純C/C++ MD5


資料來源:https://mp.weixin.qq.com/s/BHlaHN2_c2tx8D56FjfkZw


GITHUB: https://github.com/jash-git/C_MD5


code:

#include <stdio.h>
#include <stdlib.h>
#include "md5.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

/*
//字串範例
int main( void )
{
    int read_len;
    int i ;
    char temp[8]={0};
    unsigned char digest[16]; //存放结果
    char hexbuf[128]="12334567";
    unsigned char decrypt[16]={0};
    unsigned char decrypt32[64]={0};
    MD5_CTX md5c;
    MD5Init(&md5c); //初始化
    read_len = strlen(hexbuf);
    MD5Update(&md5c,(unsigned char *)hexbuf,read_len);
    MD5Final(&md5c,decrypt);
    strcpy((char *)decrypt32,"");
    for(i=0;i<16;i++)
    {
        sprintf(temp,"%02x",decrypt[i]);
        strcat((char *)decrypt32,temp);
    }
    printf("md5:%s\n",decrypt32);
    return 0;
}
*/

//檔案範例
#define FORWORD_FW "main.c"

int calc_md5(char*filename,char*dest)
{
    int i;
    int filelen = 0;
    int read_len;
    char temp[8]={0};
    char hexbuf[128]={0};
    unsigned char decrypt[16]={0};
    unsigned char decrypt32[64]={0};
    MD5_CTX md5;
    char fw_path[128];

    int fdf;

    fdf = open(filename,O_RDWR);
    if(fdf<0)
    {
        printf("%s not exist\n",FORWORD_FW);
        return -1;
    }

    MD5Init(&md5);
    while(1)
    {
        read_len = read(fdf, hexbuf,sizeof(hexbuf));
        if (read_len <0)
        {
            close(fdf);
            return -1;
        }
        if(read_len==0)
        {
            break;
        }
        filelen += read_len;
        MD5Update(&md5,(unsigned char *)hexbuf,read_len);
    }


    MD5Final(&md5,decrypt);
    strcpy((char *)decrypt32,"");

    for(i=0;i<16;i++)
    {
        sprintf(temp,"%02x",decrypt[i]);
        strcat((char *)decrypt32,temp);
    }
    strcpy(dest,decrypt32);

    printf("md5:%s len=%d\n",dest,filelen);
    close(fdf);

    return filelen;
}

int main(int argc, char *argv[])
{
    int ret;
    int filelen;
    char md5_str[64]={0};
    char cmd[256]={0};

    filelen = calc_md5(FORWORD_FW,md5_str);
    if(filelen<0)
    {
        printf("calc_md5 fail\n");
        return -1;
    }
    return 0;
}

 

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *