OpenSSL安装:
1.github下载最新的OpenSSL:https://github.com/openssl/openssl
2.在linux解压压缩包
3.安装OpenSSL
1 ./config --prefix=/usr/local --openssldir=/usr/local/ssl 2 make && make install 3 ./config shared --prefix=/usr/local --openssldir=/usr/local/ssl 4 make clean 5 make && make install
4.用ln将需要的so文件链接到/usr/lib或者/lib这两个默认的目录下面
1 ln -s /where/you/install/lib/*.so /usr/lib 2 sudo ldconfig
openssl MD5接口:
1 int MD5_Init(MD5_CTX *c); 2 //初始化MD5上下文结构 3 4 int MD5_Update(MD5_CTX *c, const void *data, size_t len); 5 //刷新MD5,将文件连续数据分片放入进行MD5刷新。 6 7 int MD5_Final(unsigned char *md, MD5_CTX *c); 8 //产生最终的MD5数据 9 10 unsigned char *MD5(const unsigned char *d, size_t n, unsigned char *md); 11 //直接产生字符串的MD5
代码实现:
1 #include <iostream> 2 #include <fstream> 3 #include <iomanip> 4 #include <string> 5 #include <openssl/md5.h> 6 7 using namespace std; 8 9 #define MAXDATABUFF 1024 10 #define MD5LENTH 16 11 12 int main(int arc,char *arv[]) 13 { 14 string strFilePath = arv[1]; 15 ifstream ifile(strFilePath.c_str(),ios::in|ios::binary); //打开文件 16 unsigned char MD5result[MD5LENTH]; 17 do 18 { 19 if (ifile.fail()) //打开失败不做文件MD5 20 { 21 cout<<"open file failure!so only display string MD5!"<<endl; 22 break; 23 } 24 MD5_CTX md5_ctx; 25 MD5_Init(&md5_ctx); 26 27 char DataBuff[MAXDATABUFF]; 28 while(!ifile.eof()) 29 { 30 ifile.read(DataBuff,MAXDATABUFF); //读文件 31 int length = ifile.gcount(); 32 if(length) 33 { 34 MD5_Update(&md5_ctx,DataBuff,length); //将当前文件块加入并更新MD5 35 } 36 } 37 MD5_Final(MD5result,&md5_ctx); //获取MD5 38 cout<<"file MD5:"<<endl; 39 for(int i = 0; i < MD5LENTH; i++) //将MD5以16进制输出 40 cout<< hex <<(int)MD5result[i]; 41 cout<<endl; 42 }while(false); 43 44 MD5((const unsigned char*)strFilePath.c_str(),strFilePath.size(),MD5result); //获取字符串MD5 45 cout<<"string MD5:"<<endl; 46 for(int i = 0; i < MD5LENTH; i++) 47 cout << hex << (int)MD5result[i]; 48 cout<<endl; 49 return 0; 50 }
SConstruct:
Program('md5','md5.cpp',LIBS = ['ssl','crypto'])
测试结果与命令行比较: