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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章