这篇文件借鉴网上的文件,然后自己做了一些修改,主要是对测试的过程中发现一些不一致和不详尽导致一些麻烦的解决
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 是要去掉换行,要不是不对的