2022年8月14日 星期日

RFC 1319 - MD2 Message-Digest Algorithm


Message Digest 演算法是以隨意長度的message作為input, 並產生128-bit的"fingerprint"或"message "digest". 雖然RFC後面有附上實作, 但是網路上這篇比較容易閱讀, 有助於理解MD2的演算法,
/**
 * @file md2.c
 * @author .ukasz Grudnik (https://github.com/lukaszgrudnik)
 * @brief MD2 algorithm based on RFC documentation https://datatracker.ietf.org/doc/html/rfc1319
 * @version 0.1
 * @date 2022-06-26
 *
 * @copyright Copyright (c) 2022
 *
 */

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

// This step uses a 256-byte "random" permutation constructed from the
//    digits of pi. Let S[i] denote the i-th element of this table.
static unsigned char S[256] = {
    41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6,
    19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188,
    76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24,
    138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251,
    245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63,
    148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50,
    39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165,
    181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210,
    150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157,
    112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27,
    96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15,
    85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197,
    234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65,
    129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123,
    8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233,
    203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228,
    166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237,
    31, 26, 219, 153, 141, 51, 159, 17, 131, 20
};

int main(int argc, char *argv[])
{

    if (argc == 1) {
        printf("error: Type message to hash\n");
        printf("./a.out <message>\n");
        return -1;
    }

    // Step 1. Append Padding Bytes
    int p, N, n;


    // The message is "padded" (extended) so that its length (in bytes) is
    //   congruent to 0, modulo 16.
    n = strlen(argv[1]) * sizeof(unsigned char);
    p = 16 - n % 16;
    N = n + p;

    unsigned char *M = (unsigned char *)malloc(N);

    // Padding is performed as follows: "i" bytes of value "i" are appended
    //   to the message so that the length in bytes of the padded message
    //   becomes congruent to 0, modulo 16. At least one byte and at most 16
    //   16 bytes are appended.
    memcpy(M, argv[1], n);
    memset(M+n, p, p);

    // Step 2. Append Checksum
    // Clear checksum.
    unsigned char C[16];
    memset(C, 0, 16);

    unsigned char c;
    // Set L to 0.
    unsigned char L = 0;

    // Process each 16-word block.
    for (int i = 0; i <= N / 16 - 1; i++) {
        for (int j = 0; j <= 15; j++) {
            c = M[i * 16 + j]; // Set c to M[i*16+j]
            C[j] ^= S[c ^ L];  // Set C[j] to S[c xor L]
            L = C[j];          // Set L to C[j]
        }
    }

    // The 16-byte checksum C[0 ... 15] is appended to the message
    // Let M[0] with checksum), where N' = N + 16.
    int N_ = N + 16;
    unsigned char *M_ = (unsigned char *)malloc(N_);

    memcpy(M_, M, N);
    memcpy(M_ + N, C, 16);

    //  Step 3. Initialize MD Buffer
    //  A 48-byte buffer X is used to compute the message digest.
    //  The buffer is initialized to zero.
    unsigned char X[48] = {0};

    //  Step 4. Process Message in 16-Byte Blocks
    unsigned int t = 0;

    for (int m = 0; m < 16; m++) {
        printf("%d ", M_[N + m]);
    }

    // Process each 16-word block
    for (int i = 0; i <= (N_ / 16) - 1; i++) {
        // Copy block i into X.
        for (int j = 0; j <= 15; j++) {
            X[16 + j] = M_[16 * i + j]; // Set X[16+j] to M[i*16+j].
            X[32 + j] = (X[16 + j] ^ X[j]); // Set X[32+j] to (X[16+j] xor X[j])
        }

        // Set t to 0.
        t = 0;
        // Do 18 rounds.
        for (int j = 0; j <= 17; j++) {
            for (int k = 0; k <= 47; k++) {
                t = X[k] ^= S[t]; // Set t and X[k] to (X[k] xor S[t]).
            }
            t = (t + j) % 256; // Set t to (t+j) modulo 256.
        }
    }

    // Step 5. Output
    printf("\nHash:\n");
    for (int i = 0; i < 48; i++) {
        printf("%02x ", X[i]);
    }
    return 0;
}

    參考資料:
  • https://www.ietf.org/rfc/rfc1319.txt
  • https://github.com/lukaszgrudnik/MD2
  • https://nickthecrypt.medium.com/cryptography-hash-method-md2-message-digest-2-step-by-step-explanation-made-easy-with-python-10faa2e35e85




2022年7月10日 星期日

CMake - Step 4: Installing and Testing - Testing


這章節要來解釋如何在CMAKE中加入auto test功能, 主要是透過enable_testing()啟動testing功能, 並透過add_test()間接呼叫ctest執行測試, 以及set_tests_properties(PROPERTIES PASS_REGULAR_EXPRESSION)來驗證執行結果
# Require a minimum version of cmake.
# cmake_minimum_required(VERSION <min>>[...<policy_max>] [FATAL_ERROR])
cmake_minimum_required(VERSION 3.10)

# Set the name of the project.
# project(<PROJECT-NAME< [<anguage-name>...])
# project(<PROJECT-NAME>
#         [VERSION <major>[.<minor>[.<patch>[.<tweak>]]]]
#         [DESCRIPTION <project-description-string>]
#         [LANGUAGES <language-name>...])
project(Tutorial VERSION 0.1.2.3 DESCRIPTION "This is Brook 1st CMake Lib")

# Add an executable to the project using the specified source files.
# add_executable(<name> [WIN32] [MACOSX_BUNDLE]
#                [EXCLUDE_FROM_ALL]
#                [source1] [source2 ...])
add_executable(Tutorial hello.c)

# option(<variable> "" [value])
option(USE_MYMATH "Use tutorial provided math implementation" ON)

# configure_file(<input> <output>
#               [NO_SOURCE_PERMISSIONS | USE_SOURCE_PERMISSIONS |
#                FILE_PERMISSIONS <permissions>...]
#               [COPYONLY] [ESCAPE_QUOTES] [@ONLY]
#               [NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])
# configure a header file to pass some of the CMake settings
# to the source code
configure_file(Config.h.in Config.h)

if (USE_MYMATH)
# Add a subdirectory to the build.
# add_subdirectory(source_dir [binary_dir]
#                        [EXCLUDE_FROM_ALL])
add_subdirectory(mymath01)

# list(APPEND <list> [<element> ...])
# Appends elements to the list.
# If no variable named <list> exists in the current
# scope its value is treated as empty and the elements
# are appended to that empty list.
list(APPEND EXTRA_LIBS MyMathLib1)
else()
list(APPEND EXTRA_LIBS "m")
endif()

# Specify libraries or flags to use when linking a given target and/or its dependents.
# target_link_libraries(<target>
#                      <PRIVATE|PUBLIC|INTERFACE> ...
#                      [<PRIVATE|PUBLIC|INTERFACE> ...]...)
target_link_libraries(Tutorial PUBLIC ${EXTRA_LIBS})

# Add include directories to a target.
# target_include_directories(<target> [SYSTEM] [AFTER|BEFORE]
#   <INTERFACE|PUBLIC|PRIVATE> [items1...]
#   [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
target_include_directories(Tutorial PUBLIC "${PROJECT_BINARY_DIR}")

# Enable testing for current directory and below.
enable_testing()

# Start recording a function for later invocation as a command.
# function(<name> [<arg1> ...])
#         <commands>
# endfunction()
function(do_test target arg result)
  # Add a test to the project to be run by ctest(1).
  #add_test(NAME <name> COMMAND <command> [<arg>...]
  #         [CONFIGURATIONS <config>...]
  #         [WORKING_DIRECTORY <dir>]
  #          [COMMAND_EXPAND_LISTS])
  # Adds a test called <name>
  add_test(NAME Comp${arg} COMMAND ${target} ${arg})

  # Set a property of the tests.
  # set_tests_properties(test1 [test2...] PROPERTIES prop1 value1 prop2 value2)
  set_tests_properties(Comp${arg}
      PROPERTIES PASS_REGULAR_EXPRESSION ${result}
  )
endfunction()

do_test(Tutorial 4 "mymath: 16")

上述範例主要透過do_test(Tutorial 4 "mymath: 16")執行測試, 而do_test為我們自訂的function, 透過add_test(NAME Comp${arg} COMMAND ${target} ${arg})執行ctest與set_tests_properties(Comp${arg} PROPERTIES PASS_REGULAR_EXPRESSION ${result})驗證執行結果, 這裡的${result}就等於"mymath: 16", 要根據輸出結果作對應修改.
執行結果如下
[brook@:~/Projects/cmake/04-2]$ mkdir build && cd build
[brook@:~/Projects/cmake/04-2/build]$ cmake ../src/ && make all test ARGS="-V"
-- The C compiler identification is GNU 7.5.0
-- The CXX compiler identification is GNU 7.5.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /build/brook/Projects/cmake/04-2/build
Scanning dependencies of target MyMathLib1
[ 25%] Building C object mymath01/CMakeFiles/MyMathLib1.dir/mymath01.c.o
[ 50%] Linking C static library libMyMathLib1.a
[ 50%] Built target MyMathLib1
Scanning dependencies of target Tutorial
[ 75%] Building C object CMakeFiles/Tutorial.dir/hello.c.o
/build/brook/Projects/cmake/04-2/src/hello.c:6:9: note: #pragma message: use mymath
 #pragma message("use mymath")
         ^~~~~~~
[100%] Linking C executable Tutorial
[100%] Built target Tutorial
Running tests...
UpdateCTestConfiguration  from :/build/brook/Projects/cmake/04-2/build/DartConfiguration.tcl
UpdateCTestConfiguration  from :/build/brook/Projects/cmake/04-2/build/DartConfiguration.tcl
Test project /build/brook/Projects/cmake/04-2/build
Constructing a list of tests
Done constructing a list of tests
Updating test list for fixtures
Added 0 tests to meet fixture requirements
Checking test dependency graph...
Checking test dependency graph end
test 1
    Start 1: Comp4

1: Test command: /build/brook/Projects/cmake/04-2/build/Tutorial "4"
1: Test timeout computed to be: 9.99988e+06
1: mymath: 16
1/1 Test #1: Comp4 ............................   Passed    0.01 sec

100% tests passed, 0 tests failed out of 1

Total Test time (real) =   0.01 sec
[brook@:~/Projects/cmake/04-2/build]$ cmake ../src/ && make all test
-- Configuring done
-- Generating done
-- Build files have been written to: /build/brook/Projects/cmake/04-2/build
[ 50%] Built target MyMathLib1
[100%] Built target Tutorial
Running tests...
Test project /build/brook/Projects/cmake/04-2/build
    Start 1: Comp4
1/1 Test #1: Comp4 ............................   Passed    0.00 sec

100% tests passed, 0 tests failed out of 1

Total Test time (real) =   0.01 sec


利用make test ARGS="-V"多印一些ctest的output, 這樣比較容易debug


2022年7月2日 星期六

CMake - Step 4: Installing and Testing - Installing


install() 用來產生installation rules, 這個章節主要談兩個install指令,install(TARGETS)與install(FILES).cmake的install選像是在3.15之後才支援, 之前的版本請直接用"make install [DESTDIR=<destdir>]
          
[brook@:~/Projects/cmake/04]$ tree
.
`-- src
    |-- CMakeLists.txt
    |-- Config.h.in
    |-- hello.c
    `-- mymath01
        |-- CMakeLists.txt
        |-- mymath01.c
        `-- mymath01.h

2 directories, 6 files
[brook@:~/Projects/cmake/04]$ cat src/CMakeLists.txt
# Require a minimum version of cmake.
# cmake_minimum_required(VERSION <min>[...<policy_max>] [FATAL_ERROR])
cmake_minimum_required(VERSION 3.10)

# Set the name of the project.
# project(<PROJECT-NAME< [<anguage-name>...])
# project(<PROJECT-NAME>
#         [VERSION <major>[.<minor>[.<patch>[.<tweak>]]]]
#         [DESCRIPTION <project-description-string>]
#         [LANGUAGES <language-name>...])
project(Tutorial VERSION 0.1.2.3 DESCRIPTION "This is Brook 1st CMake Lib")

# Add an executable to the project using the specified source files.
# add_executable(<name> [WIN32] [MACOSX_BUNDLE]
#                [EXCLUDE_FROM_ALL]
#                [source1] [source2 ...])
add_executable(Tutorial hello.c)

# option(<variable> "<help_text>" [value])
option(USE_MYMATH "Use tutorial provided math implementation" ON)

# configure_file(<input> <output>
#               [NO_SOURCE_PERMISSIONS | USE_SOURCE_PERMISSIONS |
#                FILE_PERMISSIONS <permissions>...]
#               [COPYONLY] [ESCAPE_QUOTES] [@ONLY]
#               [NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])
# configure a header file to pass some of the CMake settings
# to the source code
configure_file(Config.h.in Config.h)

if (USE_MYMATH)
# Add a subdirectory to the build.
# add_subdirectory(source_dir [binary_dir]
#                        [EXCLUDE_FROM_ALL])
add_subdirectory(mymath01)

# list(APPEND <list> [<element> ...])
# Appends elements to the list.
# If no variable named <list> exists in the current
# scope its value is treated as empty and the elements
# are appended to that empty list.
list(APPEND EXTRA_LIBS MyMathLib1)
else()
list(APPEND EXTRA_LIBS "m")
endif()

# Specify libraries or flags to use when linking a given target and/or its dependents.
# target_link_libraries(<target>
#                      <PRIVATE|PUBLIC|INTERFACE> ...
#                      [<PRIVATE|PUBLIC|INTERFACE> ...]...)
target_link_libraries(Tutorial PUBLIC ${EXTRA_LIBS})

# Add include directories to a target.
# target_include_directories(<target> [SYSTEM] [AFTER|BEFORE]
#   <INTERFACE|PUBLIC|PRIVATE> [items1...]
#   [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
target_include_directories(Tutorial PUBLIC "${PROJECT_BINARY_DIR}")

install(TARGETS Tutorial DESTINATION bin)
install(FILES "${PROJECT_BINARY_DIR}/Config.h" DESTINATION include)

[brook@:~/Projects/cmake/04]$ cat src/mymath01/CMakeLists.txt
# Add a library to the project using the specified source files.
# add_library(<name> [STATIC | SHARED | MODULE]
#             [EXCLUDE_FROM_ALL]
#                       source1 [source2 ...])
add_library(MyMathLib1 mymath01.c)

# target_include_directories(<target> [SYSTEM] [AFTER|BEFORE]
#  <INTERFACE|PUBLIC|PRIVATE> [items1...]
#    [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
# target_include_directories(MyMathLib1 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_include_directories(MyMathLib1 INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})

# install(TARGETS targets... [EXPORT <export-name>]
#        [RUNTIME_DEPENDENCIES args...|RUNTIME_DEPENDENCY_SET <set-name>]
#        [[ARCHIVE|LIBRARY|RUNTIME|OBJECTS|FRAMEWORK|BUNDLE|
#          PRIVATE_HEADER|PUBLIC_HEADER|RESOURCE|FILE_SET <set-name>]
#          [DESTINATION <dir>]
#          [PERMISSIONS permissions...]
#          [CONFIGURATIONS [Debug|Release|...]]
#          [COMPONENT <component>]
#          [NAMELINK_COMPONENT <component>]
#          [OPTIONAL] [EXCLUDE_FROM_ALL]
#          [NAMELINK_ONLY|NAMELINK_SKIP]
#          ] [...]
#         [INCLUDES DESTINATION [<dir> ...]]
install(TARGETS MyMathLib1 DESTINATION lib)

# install(<FILES|PROGRAMS> files...
#        TYPE <type> | DESTINATION <dir>
#              [PERMISSIONS permissions...]
#              [CONFIGURATIONS [Debug|Release|...]]
#              [COMPONENT <component>]
#              [RENAME <name>] [OPTIONAL] [EXCLUDE_FROM_ALL])
install(FILES mymath01.h DESTINATION include)

[brook@:~/Projects/cmake/04]$ mkdir build && cd build
[brook@:~/Projects/cmake/04/build]$ cmake ../src
-- The C compiler identification is GNU 7.5.0
-- The CXX compiler identification is GNU 7.5.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /build/brook/Projects/cmake/04/build
[brook@:~/Projects/cmake/04/build]$ cmake --build .
Scanning dependencies of target MyMathLib1
[ 25%] Building C object mymath01/CMakeFiles/MyMathLib1.dir/mymath01.c.o
[ 50%] Linking C static library libMyMathLib1.a
[ 50%] Built target MyMathLib1
Scanning dependencies of target Tutorial
[ 75%] Building C object CMakeFiles/Tutorial.dir/hello.c.o
/build/brook/Projects/cmake/04/src/hello.c:6:9: note: #pragma message: use mymath
 #pragma message("use mymath")
         ^~~~~~~
[100%] Linking C executable Tutorial
[100%] Built target Tutorial
[brook@:~/Projects/cmake/04/build]$ make install
[ 50%] Built target MyMathLib1
[100%] Built target Tutorial
Install the project...
-- Install configuration: ""
-- Installing: /usr/local/bin/Tutorial
CMake Error at cmake_install.cmake:47 (file):
  file INSTALL cannot copy file
  "/build/brook/Projects/cmake/04/build/Tutorial" to
  "/usr/local/bin/Tutorial".


Makefile:117: recipe for target 'install' failed
make: *** [install] Error 1
[brook@:~/Projects/cmake/04/build]$ make install DESTDIR=/build/brook/Projects/cmake
[ 50%] Built target MyMathLib1
[100%] Built target Tutorial
Install the project...
-- Install configuration: ""
-- Installing: /build/brook/Projects/cmake/usr/local/bin/Tutorial
-- Installing: /build/brook/Projects/cmake/usr/local/include/Config.h
-- Installing: /build/brook/Projects/cmake/usr/local/lib/libMyMathLib1.a
-- Installing: /build/brook/Projects/cmake/usr/local/include/mymath01.h
[brook@:~/Projects/cmake/04/build]$ tree /build/brook/Projects/cmake/usr/
/build/brook/Projects/cmake/usr/
`-- local
    |-- bin
    |   `-- Tutorial
    |-- include
    |   |-- Config.h
    |   `-- mymath01.h
    `-- lib
        `-- libMyMathLib1.a

4 directories, 4 files


這裡的install主要用了Target/FILES兩個選項, 再搭配DESTINATION參數, DESTINATION是指要安裝到哪個目錄去, 可以是相對路徑或是絕對路徑(relative or absolute paths). 可以透過CMAKE_INSTALL_PREFIX在cmake時設定prefix, 或在make時透過DESTDIR去改變
          
[brook@:~/Projects/cmake/04/src]$ cmake -DCMAKE_INSTALL_PREFIX=/build/brook/Projects/cmake
-- The C compiler identification is GNU 7.5.0
-- The CXX compiler identification is GNU 7.5.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /build/brook/Projects/cmake/04/src
[brook@:~/Projects/cmake/04/src]$ cmake --build .
Scanning dependencies of target MyMathLib1
[ 25%] Building C object mymath01/CMakeFiles/MyMathLib1.dir/mymath01.c.o
[ 50%] Linking C static library libMyMathLib1.a
[ 50%] Built target MyMathLib1
Scanning dependencies of target Tutorial
[ 75%] Building C object CMakeFiles/Tutorial.dir/hello.c.o
/build/brook/Projects/cmake/04/src/hello.c:6:9: note: #pragma message: use mymath
 #pragma message("use mymath")
         ^~~~~~~
[100%] Linking C executable Tutorial
[100%] Built target Tutorial
[brook@:~/Projects/cmake/04/src]$ make install
[ 50%] Built target MyMathLib1
[100%] Built target Tutorial
Install the project...
-- Install configuration: ""
-- Installing: /build/brook/Projects/cmake/bin/Tutorial
-- Installing: /build/brook/Projects/cmake/include/Config.h
-- Installing: /build/brook/Projects/cmake/lib/libMyMathLib1.a
-- Installing: /build/brook/Projects/cmake/include/mymath01.h
[brook@:~/Projects/cmake/04/src]$ make install DESTDIR=/build/brook/Projects/cmake/04
[ 50%] Built target MyMathLib1
[100%] Built target Tutorial
Install the project...
-- Install configuration: ""
-- Installing: /build/brook/Projects/cmake/04/build/brook/Projects/cmake/bin/Tutorial
-- Installing: /build/brook/Projects/cmake/04/build/brook/Projects/cmake/include/Config.h
-- Installing: /build/brook/Projects/cmake/04/build/brook/Projects/cmake/lib/libMyMathLib1.a
-- Installing: /build/brook/Projects/cmake/04/build/brook/Projects/cmake/include/mymath01.h



熱門文章