OpenSSL - 文件和字符MD5加密實現


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'])

 

測試結果與命令行比較

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM