标签:argv ring cond ++ pen cte #define std streams
CppMD5Demo.cpp
#include <iostream> #include <fstream> #include <chrono> #include "MessageDigest5.h" #define INPUT_BUFFER_SIZE 1024 int main(int argc, const char **argv) { if (argc < 3) std::cout << "Usage: CppMD5Demo [options] <param>\nOptions:\n -string <string>\n -file <filename>" << std::endl; else { if (!std::strcmp(argv[1], "-string")) { const std::chrono::system_clock::time_point &startTime = std::chrono::system_clock::now(); MessageDigest5 md5; md5.appendData(argv[2], std::strlen(argv[2])); const std::string &md5String = md5.result(); const std::chrono::system_clock::time_point &endTime = std::chrono::system_clock::now(); const std::chrono::duration<float, std::ratio<1, 1>> &elapseTime = endTime - startTime; std::cout << "MD5 hashed: " << md5String << ", elapsed time: " << elapseTime.count() << " seconds." << std::endl; } else if (!std::strcmp(argv[1], "-file")) { std::ifstream ifs(argv[2], std::ifstream::binary); if (ifs.is_open()) { std::cout << "MD5 hashing..." << std::endl; const std::chrono::system_clock::time_point &startTime = std::chrono::system_clock::now(); MessageDigest5 md5; char buffer[INPUT_BUFFER_SIZE]; while (!ifs.eof()) { std::streamsize numberOfCharacters = ifs.read(buffer, INPUT_BUFFER_SIZE).gcount(); md5.appendData(buffer, numberOfCharacters); } const std::string &md5String = md5.result(); const std::chrono::system_clock::time_point &endTime = std::chrono::system_clock::now(); const std::chrono::duration<float, std::ratio<1, 1>> &elapsedTime = endTime - startTime; std::cout << "MD5 hashed: " << md5String << ", elapsed time: " << elapsedTime.count() << " seconds." << std::endl; } else std::cout << "Cannot open file: " << argv[2] << std::endl; } else std::cout << "Usage: CppMD5Demo [options] <param>\nOptions:\n -string <string>\n -file <filename>" << std::endl; } return 0; }
MessageDigest5.h
#pragma once #include <string> #include "libmd5/md5.h" class MessageDigest5 { public: MessageDigest5(); void appendData(const char *data, size_t dataSize); std::string result(); private: md5_state_t md5State; };
MessageDigest5.cpp
#include "MessageDigest5.h" MessageDigest5::MessageDigest5() { md5_init(&md5State); } void MessageDigest5::appendData(const char *data, size_t dataSize) { md5_append(&md5State, reinterpret_cast<const md5_byte_t *>(data), dataSize); } std::string MessageDigest5::result() { unsigned char digest[16]; md5_finish(&md5State, digest); std::string md5String; char hexBuffer[3]; for (size_t i = 0; i != 16; ++i) { if (digest[i] < 16) sprintf(hexBuffer, "0%x", digest[i]); else sprintf(hexBuffer, "%x", digest[i]); md5String.append(hexBuffer); } return md5String; }
关于libmd5,可参考使用C语言获取字符串或文件的MD5值
标签:argv ring cond ++ pen cte #define std streams
原文地址:https://www.cnblogs.com/buyishi/p/9100257.html