Ubuntu/linux调用md5加密数据/文件

安装库

sudo apt-get install openssl

sudo apt-get install libssl-dev

编写程序

//gcc -g str_md5_demo.c -o str_md5_demo -lcrypto
//
#include 
#include 
#include 
 
int main(int argc, char* argv[]){
    MD5_CTX ctx;
    unsigned char md[16] = {0};
    int i = 0;
 
    //方法一:
    MD5_Init(&ctx);
    MD5_Update(&ctx, "hel", 3);
    MD5_Update(&ctx, "lo", 2);
    MD5_Final(md, &ctx);
 
    for (i = 0; i < 16; i++)
        printf("%02X", md[i]);
    printf("\n");
 
    //方法二:
    const char data[] = "hello";
    MD5(data, strlen(data), md);
 
    for (i = 0; i < 16; i++)
        printf("%02X", md[i]);
    printf("\n");
 
    return 0;
}

//gcc -g file_md5_demo.c -o file_md5_demo -lcrypto
//
 
#include 
#include 
#include 
 
int main(int argc, char* argv[]){
    MD5_CTX ctx;
    unsigned char md[16] = {0};
    char buffer[1024] = {0};
    char filename[64] = {0};
    int len = 0, i;
    FILE* fp = NULL;
 
    printf("请输入文件名, 用于计算MD5值\n");
    scanf("%s", filename);
 
    fp = fopen(filename, "rb");
    if(NULL == fp){
        printf("can't open file\n");
        return 1;
    }
 
    //方法一:
    MD5_Init(&ctx);
    while((len=fread(buffer, 1, sizeof(buffer), fp)) > 0){
        MD5_Update(&ctx, buffer, len);
        memset(buffer, 0 ,sizeof(buffer));
    }
    MD5_Final(md, &ctx);
 
    for(i=0; i<16; i++)
        printf("%02X", md[i]);
    printf("\n");
 
    //方法二:
    while((len=fread(buffer, 1, sizeof(buffer), fp)) > 0){
        MD5(buffer, len, md);
        memset(buffer, 0 ,sizeof(buffer));
    }
 
    for(i=0; i<16; i++)
        printf("%02X", md[i]);
    printf("\n");
 
    if(fp) fclose(fp);
 
    return 0;
}

编写Makefile

注意:在Ubuntu 14.04 64bit上一定要需要链接 -lcrypto

INCLUDES = -I. -I /usr/include/http-test
SRCS = http-test.c
OBJS = $(SRCS:.c=.o)
CC = gcc
CFLAGS = -Wall -O -g
LIBS = -lpthread -lcrypto
EXE = http-test

$(EXE):$(OBJS)
	$(CC) $^ -o $@ $(LIBS)

%.o: %.c
	$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

clean:
	rm -f $(EXE) $(OBJS)

你可能感兴趣的:(Linux,MT7688)