Linux下MD5移植和编程

来源:互联网 发布:银行家算法 0 4 2 0 编辑:程序博客网 时间:2024/06/06 16:33
1、安装MD5工具
首先下载MD5工具源码:
进入地址:http://martin.hinner.info/libmd/
下载libmd库libmd-0.3.tar.bz2
在ubuntu14.04安装libmd工具:
#tar -jxvf libmd-0.3.tar.bz2
#cd libmd-0.3
#./configure
#make

#make install

注意:在make的时候可能会出现md5.c的MD5Update()函数定义跟md5.h声明冲突,只要参数类型改成一样就可以了。


2、交叉编译MD5工具
备注:若移植至arm平台则相应改为arm-linux
#cd libmd-0.3
#./configure --host=arm-linux --prefix=/home/md5test
#vi Makefile
打开Makefile并修改:
将CC = gcc 修改为 CC =arm-linux-gcc
将RANLIB = ranlib 修改为 RANLIB = arm-linux-ranlib
将AR = ar 修改为 AR = arm-linux-ar
在INSTALL = /usr/bin/install -c语句下添加语句:
BUILDROOT = /home/md5test

#make
#make install
安装后在目录/home/md5test下生成usr/include/、usr/lib/、usr/man等文件夹,将交叉编译生成的在/home/md5test/libmd.so.1.0移至目标平台的/lib目录,完成MD5移植。


3、MD5编程
Libmd提供了一系列C函数接口,通过这些接口可方便地实现MD5加密。
md5.h文件提供了MD5编程中一个重要的结构体struct MD5Context,它的原型如下:
struct MD5Context{
u_int32_t buf[4];
U_int32_t bits[2];
Unsigned char in[64];
}MD5_CTX;
该类型结构体贯穿整个MD5编程。
3.1 MD5常用函数接口

[cpp] view plain copy
 print?
  1. #include <sys/types.h>  
  2. #include <md5.h>  
  3. void MD5Init(MD5_CTX *context);  
  4. void MD5Update(MD5_CTX *context, const void *data, unsigned int len);  
  5. void MD5Pad(MD5_CTX *context);  
  6. void MD5Final(unsigned char digest[16], MD5_CTX *context);  
  7. char *MD5End(MD5_CTX *context, char *buf);  
  8. char *MD5File(const char *filename, char *buf);  
  9. char *MD5FileChunk(const char *filename, char *buf, off_t offset, off_t lenghth);  
  10. char *MD5Data(const void *data, unsigned int len, char *buf);  
函数说明:
MD5Init(), MD5Update()和MD5Final():是核心函数,MD5编程时,先分配一个MD5_CTX结构体空间,使用MD5Init()对该结构体进行初始化,使用MD5Update()对它进行更新,最后使用MD5Final()提取结果。
MD5Pad():类似于MD5Final(),区别在于它并不会终止计算。
MD5End():是MD5Final()函数的封装,它将转换的128十六进制编码转换为一串33个字符(包含结束符'\0')的ASCII码字符串。
MD5File():计算文件的摘要,并使用MD5End()返回结果。如果指定的文件不能打开,则返回NULL指针。
MD5FileChunk():函数类似于MD5File(),但它只计算文件里指定偏移offset开始至往后length个字节的文件摘要。如果length为0,或者大于偏移后剩余的长度,则MD5FileChunk()计算从偏移出至文件结尾的文件摘要。


4、MD5加密程序例子:

#include <stdlib.h>  
#include <string.h>  
#include <stdio.h>  
#include <unistd.h>  
#include <sys/types.h>  
#include <md5.h>  
  
int main(void)  
{  
    unsigned char passwd[10] = {"1234567"};  
    unsigned char out[100] = {0};  
    int i;  
  
    MD5_CTX ctx;  
    memset(&ctx, 0, sizeof(MD5_CTX));  
  
    MD5Init(&ctx);  
    MD5Update(&ctx, (unsigned char*)passwd,(unsigned)strlen(passwd));  
    MD5Final((unsigned char *)out, &ctx);  
  
    printf("MD5 code is:\n");  
    for(i = 0; i < 100; i++)  
    {  
        printf("%02x ", out[i]);  
    }  
    printf("\n");  
    return 0;  
}  


ubuntu本机编译:

gcc md5.c -o md5test -lmd

./md5test

MD5 code is:
fc ea 92 0f 74 12 b5 da 7b e0 cf 42 b8 c9 37 59

上面产生的字段为passwd经过MD5加密后的128位编码。


交叉编译与运行:
#arm-linux-gcc -I/home/md5test/usr/include -o md5test md5.c -L/home/md5test/usr/lib -lmd
将可执行文件md5拷至目标平台运行可得到跟上面一样的加密编码。