From d599dd9a681d815dd6627b358ee36b5a6354f6c0 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Sat, 16 Apr 2016 16:51:46 +0300 Subject: [PATCH] Add an example program demonstrating hash API Also useful for verifying the implementations. --- .gitignore | 1 + Build | 6 ++++ examples/checksum.cpp | 75 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 82 insertions(+) create mode 100644 examples/checksum.cpp diff --git a/.gitignore b/.gitignore index 536c16b..87f978a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .config temp +/checksum /libmspcrypto.a /libmspcrypto.so /mspcrypto.pc diff --git a/Build b/Build index 003e9e3..9b96d9e 100644 --- a/Build +++ b/Build @@ -14,4 +14,10 @@ package "mspcrypto" map "source" "include/msp/crypto"; }; }; + + program "checksum" + { + source "examples/checksum.cpp"; + use "mspcrypto"; + }; }; diff --git a/examples/checksum.cpp b/examples/checksum.cpp new file mode 100644 index 0000000..f5ef853 --- /dev/null +++ b/examples/checksum.cpp @@ -0,0 +1,75 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace Msp; + +class Checksum: public Msp::RegisteredApplication +{ +private: + bool do_md5; + bool do_sha256; + bool do_sha512; + list files; + +public: + Checksum(int, char **); + + virtual int main(); +private: + template + void process_file(const std::string &); +}; + +Checksum::Checksum(int argc, char **argv): + do_md5(false), + do_sha256(false), + do_sha512(false) +{ + + GetOpt getopt; + getopt.add_option("md5", do_md5, GetOpt::NO_ARG); + getopt.add_option("sha256", do_sha256, GetOpt::NO_ARG); + getopt.add_option("sha512", do_sha512, GetOpt::NO_ARG); + getopt.add_argument("file", files, GetOpt::REQUIRED_ARG); + getopt(argc, argv); + + if(!do_md5 && !do_sha256 && !do_sha512) + do_md5 = true; +} + +int Checksum::main() +{ + for(list::const_iterator i=files.begin(); i!=files.end(); ++i) + { + if(do_md5) + process_file(*i); + if(do_sha256) + process_file(*i); + if(do_sha512) + process_file(*i); + } + return 0; +} + +template +void Checksum::process_file(const string &fn) +{ + IO::BufferedFile infile(fn); + H hash; + while(1) + { + char buffer[16384]; + unsigned len = infile.read(buffer, sizeof(buffer)); + if(!len) + break; + hash.update(buffer, len); + } + IO::print("%s %s\n", hash.get_hexdigest(), fn); +} -- 2.45.2