Linux下用openssl库做md5加密

这篇文件借鉴网上的文件,然后自己做了一些修改,主要是对测试的过程中发现一些不一致和不详尽导致一些麻烦的解决

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 是要去掉换行,要不是不对的


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值