使用openssl就算文件的MD5和SHA1值

来源:互联网 发布:mac u盘 200m 编辑:程序博客网 时间:2024/05/29 12:49

    在windows环境下利用VS2012计算文件的MD5和SHA1值,使用openssl动态链接库。

    程序分为两部分,第一部分计算MD5,第二部分计算SHA1。

#include <iostream>#include <sys/stat.h>  #include <openssl/md5.h> #include <openssl/sha.h> #pragma comment(lib, "libeay32.lib")#pragma comment(lib, "ssleay32.lib")int file_size(char* filename)  //文件大小{      struct stat statbuf;      stat(filename,&statbuf);      int size=statbuf.st_size;      return size;   }  int main(){MD5_CTX ctx = { 0 };int len = 0;unsigned char buffer[1024] = {0};unsigned char digest[16] = {0};int SIZE;    FILE    *fp = NULL;    char fname[50];//用于存放文件名    std::cout<<"输入文件名:";    std::cin>>fname;    fp = fopen(fname,"r");//只供读取if(fp==NULL){std::cout<<"open failed"<<std::endl;    return -1;}MD5_Init (&ctx);while ((len = fread (buffer, 1, 1024, fp)) > 0){MD5_Update (&ctx, buffer, len);}MD5_Final (digest, &ctx);char buf1[33] = {0};char tmp1[3] = {0};for(int i = 0; i < 16; i++ ){sprintf(tmp1,"%02X", digest[i]); strcat(buf1, tmp1);     }    std::cout << "MD5:"<<buf1 << std::endl;  // 文件的md5值SHA_CTX c ={ 0 };      unsigned char md[20] = {0};SIZE=file_size(fname);    SHA1((unsigned char *)fp, SIZE, md);      SHA1_Init(&c);      while ((len = fread (buffer, 1, 1024, fp)) > 0){SHA1_Update (&c, buffer, len);}    SHA1_Final(md, &c);     fclose(fp);    char buf2[41] = {0};      char tmp2[3] = {0};     for(int i = 0; i < 20; i++ )      {          sprintf(tmp2,"%02X", md[i]);          strcat(buf2, tmp2);      }  std::cout <<"SHA1:"<< buf2 <<std::endl;  // 文件的sha1值return 0;}


1 0
原创粉丝点击