這篇檔案借鑒網上的檔案,然後自己做了一些修改,主要是對測試的過程中發現一些不一致和不詳盡導致一些麻煩的解決
openssl安裝
Centos yum install openssl openssl-devel
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <openssl/md5.h>int main(int argc, char** argv) { MD5_CTX hash_ctx; char input_string[128]; unsigned char hash_ret[16]; int i; // check usage if (argc != 2) { fprintf(stderr, "%s <input string>\n", argv[0]); exit(-1); } // set the input string,這裡有個換行的檔案,如果加上換行給變數,值就不對了 snprintf(input_string, sizeof(input_string), "%s", argv[1]); // initialize a hash context MD5_Init(&hash_ctx); // update the input string to the hash context (you can update // more string to the hash context) MD5_Update(&hash_ctx, input_string, strlen(input_string)); // compute the hash result MD5_Final(hash_ret, &hash_ctx); // print printf("Input string: %s", input_string); printf("Output string: "); for (i=0; i<32; ++i) { if (i % 2 == 0) { printf("%x", (hash_ret[i/2] >> 4) & 0xf); } else { printf("%x", (hash_ret[i/2]) & 0xf); } } printf("\n"); return 0;}
編譯下看看, 需要連結openssl庫
gcc -lcrypto main2.c -o main2
測試資料
./main2 1234
Input string: 1234Output string: 81dc9bdb52d04dc20036dbd8313ed055
對比輸出是否正確,找個正確的工具對下,linux 下有md5sum
echo -n "1234"| md5sum -
echo -n 是要去掉換行,要不是不對的