CMakeLists.txt:
$ cat CMakeLists.txt
cmake_minimum_required(VERSION 3.11)
project (MD5)
SET(SOURCE_DIR ${CMAKE_SOURCE_DIR}/src)
# macOS
# $ mkdir b ; cd b;
# $ cmake .. -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl -DOPENSSL_LIBRARIES=/usr/local/opt/openssl/lib
#
find_package(OpenSSL REQUIRED)
include_directories(${OPENSSL_INCLUDE_DIR})
ADD_EXECUTABLE(main
${SOURCE_DIR}/main.c
)
TARGET_LINK_LIBRARIES(main OpenSSL::SSL)
程式碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
const char * get_md5_string(const unsigned char *in, char *output) {
int i;
for(i = 0 ; i < MD5_DIGEST_LENGTH ; i++) {
sprintf(output + (i)*2, "%02x", in[i]);
}
output[MD5_DIGEST_LENGTH*2] = '\0';
return output;
}
int main(int argc, char *argv[]) {
unsigned char digest[MD5_DIGEST_LENGTH];
char readable_digest[MD5_DIGEST_LENGTH*2 + 1];
char *test = "HelloWorld";
char *input;
if (argc > 1)
input = argv[1];
else
input = test;
MD5_CTX context;
MD5_Init(&context);
MD5_Update(&context, input, strlen(input));
MD5_Final(digest, &context);
get_md5_string(digest, readable_digest);
printf("MD5: [%s]\n", readable_digest);
return 0;
}
編譯跟運行:
$ mkdir b
$ cd b ; çmake ..
$ make
$ ./main HelloWorld
MD5: [68e109f0f40ca72a15e05cc22786f8e6]
$ echo -ne "HelloWorld" | md5
68e109f0f40ca72a15e05cc22786f8e6
沒有留言:
張貼留言