OpenSSL MD5 API


#include <stdlib.h>

#define _GNU_SOURCE /* for getline API */
#include <stdio.h>

/* OpenSSL md5 API 頭文件, 編譯時需要連接 crypto 庫(-lcrypto) */
#include <openssl/md5.h>

/* ============ OpenSSL md5 API =================
 *① 獨立API, 一次性輸入要計算的數據,然后得到md5值
 *  unsigned char *MD5(const unsigned char *src, unsigned long src_len, unsigned char *dst);
 *
 *② 系列API, 可以要計算的數據分多次輸入,然后得到md5值
 *  int MD5_Init(MD5_CTX *ctx);
 *  int MD5_Update(MD5_CTX *ctx, const void *src, unsigned long src_len);
 *  int MD5_Final(unsigned char *dst, MD5_CTX *ctx);
 *
 * Note : API輸出md5值的長度為 MD5_DIGEST_LENGTH(16個字節), 
 *        通常我們看到的md5sum等工具計算的md5值是32個字節,
 *        這是因為 API輸出的md5值是hex編碼.
 *
 */

#define md5_calc_data MD5

/* 計算文件的md5 */
unsigned char* md5_calc_file(const char* path, unsigned char *dst)
{
    FILE* fp = NULL;
    
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    
    MD5_CTX ctx;
    
    fp = fopen(path, "rb");
    if (NULL == fp) {
        return NULL;
    }
    
    MD5_Init(&ctx);
    
    while ((read = getline(&line, &len, fp)) != -1) {
        MD5_Update(&ctx, line, read);
    }
    free(line);
    MD5_Final(dst, &ctx);
    
    return dst;
}


/* 將hex編碼的MD5轉換成字符串 */
char* md5_hex2str(unsigned char* in_md5_hex, char* out_md5_str)
{
    int i = 0;

    for (i = 0; i < MD5_DIGEST_LENGTH; ++i) {
        sprintf(out_md5_str + i * 2, "%.2x", in_md5_hex[i]);
    }
    out_md5_str[MD5_DIGEST_LENGTH * 2] = '\0';

    return out_md5_str;
}

int main(void)
{
    char md5_hex[MD5_DIGEST_LENGTH]; /* len = 16 */
    char md5_str[MD5_DIGEST_LENGTH * 2 + 1]; /* len = 33 */

    md5_calc_data("hello world", sizeof("hello world")-1, md5_hex);
    md5_hex2str(md5_hex, md5_str);
    printf("[date md5]%s\n", md5_str);

    md5_calc_file("/etc/passwd", md5_hex);
    md5_hex2str(md5_hex, md5_str);
    printf("[file md5]%s\n", md5_str);

    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM