MD5
(單向散列算法)的全稱是Message-Digest Algorithm 5
(信息-摘要算法),經MD2
、MD3
和MD4
發展而來。MD5
算法的使用不須要支付任何版權費用。算法
MD5
特性:ui
輸入任意長度的信息,通過處理,輸出爲128
位的信息(數字指紋);.net
不一樣的輸入獲得的不一樣的結果(惟一性);日誌
根據128
位的輸出結果不可能反推出輸入的信息(不可逆)。code
MD5
用途:orm
防止被篡改;blog
防止直接看到明文;ip
防止抵賴(數字簽名)。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