The MD5 message-digest algorithm is a widely used cryptographic hash function producing a 128-bit (16-byte) hash value, typically expressed in text format as a 32 digit hexadecimal number. MD5 has been utilized in a wide variety of cryptographic applications, and is also commonly used to verify data integrity.
系统:Ubuntu14.04
安装:apg-get install libssl-dev
程序包含头文件:#include
编译时需指定:gcc xxxx -lcrypto
涉及到的结构体及函数:
MD5_CTX x;
int MD5_Init(MD5_CTX *c);
int MD5_Update(MD5_CTX *c, const void *data, unsigned long len);
int MD5_Final(unsigned char *md, MD5_CTX *c);
函数具体用法和介绍可通过man命令查询
下面是具体代码实现
/*
* md5加密函数,参数为需要加密字符串,返回加密后的32位16进制字符串
*/
char* md(char *src)
{
int i = 0;
MD5_CTX x;
char *out = NULL;
unsigned char d[16];
MD5_Init(&x);
MD5_Update (&x, src, strlen(src));
MD5_Final(d, &x);
out = malloc(35);
memset(out, 0x00, 35);
for (i = 0; i
{
sprintf (out + (i*2), "%02X", d[i]);
}
out[32] = 0;
return out;
}
/*
* 判断加密字符串是否在结构体md5_list中,此处未给出struct md5_list结构体具体定义。
* 若不存在,则将新字符串插入到结构体中,并返回 1
* 若存在则直接返回 0
* 具体结构体通过strcmp()函数,根据字符串之间的大小关系排序。这样排列,在查找字符串是否已经存在时,
* 只需要从前往后查找,若当前字符串比查找字符串小,下一个字符串比查找字符串大,则证明字符串不存在
*于结构体链表中,即停止向后查找,在当前位置插入字符串,这样比直接存储效率更高
*/
int check_md5(struct md5_list* list, char *src)
{
char *des = md(src);
//printf("%s\n", des);
struct md5_node *node = (struct md5_node*)malloc(sizeof(struct md5_node));
node->des = des;
node->next = NULL;
if (!list->head)
{
list->head = node;
++list->num;
return 1;
}
else
{
if (!strcmp(list->head->des, node->des))
return 0;
if (strcmp(list->head->des, node->des) > 0)
{
node->next = list->head;
list->head = node;
++list->num;
return 1;
}
else
{
struct md5_node *h = list->head;
while (h->next)
{
if (!strcmp(h->next->des, node->des))
return 0;
if (strcmp(h->next->des, node->des) > 0)
{
break;
}
h = h->next;
}
node->next = h->next;
h->next = node;
++list->num;
return 1;
}
}
}