生活随笔
收集整理的這篇文章主要介紹了
Linux下C语言使用openssl库进行MD5校验
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
http://blog.csdn.net/cassie_huang/article/details/53212933
作者:無腦仔的小明?
出處:http://www.cnblogs.com/wunaozai/?
我們以一個字符串為例,新建一個文件filename.txt,在文件內(nèi)寫入hello ,然后在Linux下可以使用命令md5sum filename.txt計算md5值 ==>?b1946ac92492d2347c6235b4d2611184 ?。雖然寫入的是hello這5個字符,但是我們使用命令xxd filename.txt后可以看出文件結(jié)尾處會有個0x0a這個回車符。所以在下面的代碼中才會有\(zhòng)n。
[cpp]?view plain
?copy ?? ?? int?MD5_Init(MD5_CTX?*c);?? ?? int?MD5_Update(MD5_CTX?*c,?const?void?*data,?size_t?len);?? ?? int?MD5_Final(unsigned?char?*md,?MD5_CTX?*c);?? ?? unsigned?char?*MD5(const?unsigned?char?*d,?size_t?n,?unsigned?char?*md);?? ?? void?MD5_Transform(MD5_CTX?*c,?const?unsigned?char?*b);??
新建一個cpp文件(C文件也可以)用于計算MD5值
[cpp]?view plain
?copy #include?<openssl/md5.h>?? #include?<string.h>?? #include?<stdio.h>?? ?? int?main()?? {?? ????MD5_CTX?ctx;?? ????unsigned?char?outmd[16];?? ????int?i=0;?? ?? ????memset(outmd,0,sizeof(outmd));?? ????MD5_Init(&ctx);?? ????MD5_Update(&ctx,"hel",3);?? ????MD5_Update(&ctx,"lo\n",3);?? ????MD5_Final(outmd,&ctx);?? ????for(i=0;i<16;i<i++)?? ????{?? ????????printf("%02X",outmd[i]);?? ????}?? ????printf("\n");?? ????return?0;?? }??
編譯選項為: g++ MD5test.cpp -lssl -o MD5test(如果是C語言可以使用gcc?MD5test.c -o ?MD5test)
運(yùn)行后的結(jié)果為:?B1946AC92492D2347C6235B4D2611184
注意這里用到openssl庫,可以自行根據(jù)網(wǎng)上教程安裝。
下面這個代碼是對文件進(jìn)行MD5計算。
[cpp]?view plain
?copy #include?<openssl/md5.h>?? #include?<string.h>?? #include?<stdio.h>?? ?? int?main()?? {?? ????MD5_CTX?ctx;?? ????unsigned?char?outmd[16];?? ????char?buffer[1024];?? ????char?filename[32];?? ????int?len=0;?? ????int?i;?? ????FILE?*?fp=NULL;?? ????memset(outmd,0,sizeof(outmd));?? ????memset(filename,0,sizeof(filename));?? ????memset(buffer,0,sizeof(buffer));?? ????printf("請輸入文件名,用于計算MD5值:");?? ????scanf("%s",filename);?? ????fp=fopen(filename,"rb");?? ????if(fp==NULL)?? ????{?? ????????printf("Can't?open?file\n");?? ????????return?0;?? ????}?? ?? ????MD5_Init(&ctx);?? ????while((len=fread(buffer,1,1024,fp))>0)?? ????{?? ????????MD5_Update(&ctx,buffer,len);?? ????????memset(buffer,0,sizeof(buffer));?? ????}?? ????MD5_Final(outmd,&ctx);?? ?? ????for(i=0;i<16;i<i++)?? ????{?? ????????printf("%02X",outmd[i]);?? ????}?? ????printf("\n");?? ????return?0;?? }??
運(yùn)行得到結(jié)果后,我們可以使用md5sum命令進(jìn)行驗證。
文章為轉(zhuǎn)載,略微改了幾個字眼。
總結(jié)
以上是生活随笔為你收集整理的Linux下C语言使用openssl库进行MD5校验的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。