OpenWrt:libubox之md5和ulog

MD5(單向散列算法)的全稱是Message-Digest Algorithm 5(信息-摘要算法),經MD2MD3MD4發展而來。MD5算法的使用不須要支付任何版權費用。算法

MD5特性:ui

  1. 輸入任意長度的信息,通過處理,輸出爲128位的信息(數字指紋);.net

  2. 不一樣的輸入獲得的不一樣的結果(惟一性);日誌

  3. 根據128位的輸出結果不可能反推出輸入的信息(不可逆)。code

MD5用途:orm

  1. 防止被篡改;blog

  2. 防止直接看到明文;ip

  3. 防止抵賴(數字簽名)。md5

md5示例代碼:ci

#include <unistd.h>
#include <string.h>
#include <stdio.h>

#include "libubox/md5.h"



void md5_data()
{
    char* data = "test data";
    unsigned char buf[16] = {0};
    md5_ctx_t ctx;

    md5_begin(&ctx);
    md5_hash(data, strlen(data), &ctx);
    md5_end(buf, &ctx);

    for(int i = 0; i < 16; i++) {
        printf("%02x", (unsigned char)buf[i]);
    }

    printf("\n");

    return;
}

void md5_file(const char* file)
{
    unsigned char buf[16] = {0};

    md5sum(file, buf);

    for(int i = 0; i < 16; i++) {
        printf("%02x", (unsigned char)buf[i]);
    }

    printf("\n");

    return;
}

int main(int argc, char** argv)
{
    int res = 0;
    int action = 0;
    char file[256] = {0};

    while((res = getopt(argc, argv, "?a:f:h")) != -1) {
        switch(res) {
        case 'a':
            action = atoi(optarg);
            break;

        case 'f':
            memcpy(file, optarg, strlen(optarg));
            break;

        case 'h':
        default:
            break;
        }
    }

    if(action == 0) {
        md5_data();
    } else if (action == 1) {
        md5_file(file);
    }

    return 0;
}

編譯後運行:

$ ./cmake-build/out/src/libubox-md5-test -a 1 -f CMakeLists.txt 
a7c99f64c37d6712ae35124d946b0bad
$ md5sum CMakeLists.txt 
a7c99f64c37d6712ae35124d946b0bad  CMakeLists.txt

日誌示例代碼:

#include <string.h>
#include <stdio.h>

#include "libubox/ulog.h"


/*
Priority Level               Description
LOG_EMERG                    An emergency situation
LOG_ALERT                    High-priority problem, such as database corruption
LOG_CRIT                     Critical error, such as hardware failure
LOG_ERR                      Errors
LOG_WARNING                  Warning
LOG_NOTICE                   Special conditions requiring attention
LOG_INFO                     Informational messages
LOG_DEBUG                    Debug messages 
*/

void log()
{
    ulog_open(ULOG_STDIO, LOG_USER, NULL);
    ulog_threshold(LOG_INFO);

    ULOG_INFO("info\n");
    ULOG_NOTE("notice\n");
    ULOG_WARN("warn\n");
    ULOG_ERR("err\n");

    ulog_close();

    return;
}

int main(int argc, char** argv)
{
    log();

    return 0;
}

運行結果:

$ ./cmake-build/out/src/libubox-ulog-test 
info
notice
warn
err

參考文章

MD5算法原理

相關文章
相關標籤/搜索