OpenWrt:libuboxのmd 5とulog

3092 ワード

MD5(一方向ハッシュアルゴリズム)のフルネームはMessage-Digest Algorithm 5(情報−要約アルゴリズム)、MD2MD3およびMD4を経て発展してきた.MD5アルゴリズムの使用は著作権料を一切支払う必要はありません.MD5特性:
  • 任意の長さの情報を入力し、処理を経て128ビットの情報(デジタル指紋)を出力する.
  • 異なる入力で得られた異なる結果(一意性);
  • 128ビットの出力結果により入力された情報を逆押しすることは不可能(不可逆).
  • MD5用途:
  • 改ざん防止;
  • 直接明文が見られないようにする.
  • 言い逃れ防止(デジタル署名).
  • md5サンプルコード:
    #include 
    #include 
    #include 
    
    #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("
    "); 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("
    "); 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 
    #include 
    
    #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
    "); ULOG_NOTE("notice
    "); ULOG_WARN("warn
    "); ULOG_ERR("err
    "); ulog_close(); return; } int main(int argc, char** argv) { log(); return 0; }

    実行結果:
    $ ./cmake-build/out/src/libubox-ulog-test 
    info
    notice
    warn
    err

    参考記事


    MD 5アルゴリズムの原理