Linux下用openssl庫做md5加密

來源:互聯網
上載者:User

這篇檔案借鑒網上的檔案,然後自己做了一些修改,主要是對測試的過程中發現一些不一致和不詳盡導致一些麻煩的解決

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.