OpenWrt:libubox之md5和ulog

MD5(单向散列算法)的全称是Message-Digest Algorithm 5(信息-摘要算法),经MD2MD3MD4发展而来。MD5算法的使用不需要支付任何版权费用。

MD5特性:

  1. 输入任意长度的信息,经过处理,输出为128位的信息(数字指纹);

  2. 不同的输入得到的不同的结果(唯一性);

  3. 根据128位的输出结果不可能反推出输入的信息(不可逆)。

MD5用途:

  1. 防止被篡改;

  2. 防止直接看到明文;

  3. 防止抵赖(数字签名)。

MD5示例代码:

#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算法原理

相关推荐