CppMD5Demo.cpp
#include <iostream>#include<fstream>#include<chrono>#include"MessageDigest5.h"#defineInput_buffer_size 1024intMainintargcConst 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")) { ConstStd::chrono::system_clock::time_point &starttime =Std::chrono::system_clock::now (); MESSAGEDIGEST5 MD5; Md5.appenddata (argv[2], Std::strlen (argv[2])); ConstSTD::string&md5string =Md5.result (); ConstStd::chrono::system_clock::time_point &endtime =Std::chrono::system_clock::now (); ConstStd::chrono::d uration<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; ConstStd::chrono::system_clock::time_point &starttime =Std::chrono::system_clock::now (); MESSAGEDIGEST5 MD5; CharBuffer[input_buffer_size]; while(!ifs.eof ()) {std::streamsize numberofcharacters=ifs.read (buffer, input_buffer_size). Gcount (); Md5.appenddata (buffer, numberofcharacters); } ConstSTD::string&md5string =Md5.result (); ConstStd::chrono::system_clock::time_point &endtime =Std::chrono::system_clock::now (); ConstStd::chrono::d uration<float, std::ratio<1,1>> &elapsedtime = endTime-StartTime; Std::cout<<"MD5 Hashed:"<< md5string <<", elapsed time:"<< Elapsedtime.count () <<"seconds."<<Std::endl; } ElseStd::cout<<"cannot open file:"<< argv[2] <<Std::endl; } ElseStd::cout<<"Usage:cppmd5demo [options] <param>\noptions:\n-string <string>\n-file <filename>"<<Std::endl; } return 0;}
MessageDigest5.h
#pragma once<string>"libmd5/md5.h" Class messagedigest5{public: MessageDigest5 (); void appendData (constChar *data, size_t datasize); std::string result (); Private : md5_state_t md5state;};
MessageDigest5.cpp
#include"MessageDigest5.h"Messagedigest5::messagedigest5 () {Md5_init (&md5state);}voidMessagedigest5::appenddata (Const Char*data, size_t datasize) {Md5_append (&md5state, reinterpret_cast<Constmd5_byte_t *>(data), datasize);} STD::stringMessagedigest5::result () {unsignedChardigest[ -]; Md5_finish (&Md5state, Digest); STD::stringmd5string; Charhexbuffer[3]; for(size_t i =0; I! = -; ++i) {if(Digest[i] < -) sprintf (Hexbuffer,"0%x", Digest[i]); Elsesprintf (Hexbuffer,"%x", Digest[i]); Md5string.append (Hexbuffer); } returnmd5string;}
For LIBMD5, refer to the MD5 value of a string or file using C language
C + + MD5 Demo