openssl/md5.h:
#define MD5_DIGEST_LENGTH 16
typedef struct MD5state_st
{
MD5_LONG A,B,C,D;
MD5_LONG Nl,Nh;
MD5_LONG data[MD5_LBLOCK];
unsigned int num;
} MD5_CTX;
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);[/code]
需要用到的接口主要就是这些了。
struct MD5state_st是md5算法要用到的ctx结构
MD5_Init 是初始化ctx结构
MD5_Update 则是对输入参数data(其长度为len)进行md5计算。
MD5_Final是最后把结果输出至缓存md中。
OK,写一个程序试试:
file:md5.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <stdio.h> #include <string.h> #include <openssl/md5.h> int main(int argc, char **argv) { MD5_CTX ctx; unsigned char *buf = "password"; unsigned char md[MD5_DIGEST_LENGTH]; int i; MD5_Init(&ctx); MD5_Update(&ctx, (void *)buf, strlen(buf)); MD5_Final(md, &ctx); printf("%s\nmd5: ", buf); for(i = 0; i< MD5_DIGEST_LENGTH; i++) printf("%02x", md[i]); printf("/n"); return 0; } |
编译:
gcc -o md5 md5.c -lcrypto