Linux开发中 MD5值的计算
生活随笔
收集整理的這篇文章主要介紹了
Linux开发中 MD5值的计算
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Go語言中crypto/md5包中提供了MD5計算的API,在Linux中,openssl庫也提供了類似的接口,編譯的時候加上鏈接選項-lcrypto 就可以使用了。
基本API有兩種,一種是MD5(),另一種是分為三個部分,MD5_Init, MD5_Update, MD5_Final,這個適合長度不確定的數據計算:
#include <openssl/md5.h>//d存儲待計算的數據,n表示數據的長度,如果md非空,則存儲md5值。unsigned char *MD5(const unsigned char *d, unsigned long n, unsigned char *md);//初始化int MD5_Init(MD5_CTX *c);//計算data中長度為len的MD5,當數據很大的情況下,可以分多次計算int MD5_Update(MD5_CTX *c, const void *data, unsigned long len);//得到累計的md5值int MD5_Final(unsigned char *md, MD5_CTX *c);測試用例:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/md5.h>char *str2md5(const char *str, int length) {int n;MD5_CTX c;unsigned char digest[16];char *out = (char*)malloc(33);MD5_Init(&c);while (length > 0) {if (length > 512) {MD5_Update(&c, str, 512);} else {MD5_Update(&c, str, length);}length -= 512;str += 512;}MD5_Final(digest, &c);for (n = 0; n < 16; ++n) {snprintf(&(out[n*2]), 16*2, "%02x", (unsigned int)digest[n]);}return out; }int main(int argc, char **argv) {char *output = str2md5("hello", strlen("hello"));printf("%s\n", output);free(output);return 0; }編譯運行:
如果出現如下編譯錯誤:
openssl/md5.h: No such file or directory解決方案: sudo apt-get install libpcap-dev libssl-dev參考文檔:
1.?https://www.openssl.org/docs/manmaster/man3/MD5.html
2.?https://stackoverflow.com/questions/7627723/how-to-create-a-md5-hash-of-a-string-in-c
?
總結
以上是生活随笔為你收集整理的Linux开发中 MD5值的计算的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: golang 编译提示 cannot a
- 下一篇: tcp/ip 协议栈Linux源码分析五