]> git.tdb.fi Git - libs/crypto.git/blob - examples/checksum.cpp
Add an example program demonstrating hash API
[libs/crypto.git] / examples / checksum.cpp
1 #include <list>
2 #include <string>
3 #include <msp/core/application.h>
4 #include <msp/core/getopt.h>
5 #include <msp/crypto/md5.h>
6 #include <msp/crypto/sha2.h>
7 #include <msp/io/file.h>
8 #include <msp/io/print.h>
9
10 using namespace std;
11 using namespace Msp;
12
13 class Checksum: public Msp::RegisteredApplication<Checksum>
14 {
15 private:
16         bool do_md5;
17         bool do_sha256;
18         bool do_sha512;
19         list<string> files;
20
21 public:
22         Checksum(int, char **);
23
24         virtual int main();
25 private:
26         template<typename H>
27         void process_file(const std::string &);
28 };
29
30 Checksum::Checksum(int argc, char **argv):
31         do_md5(false),
32         do_sha256(false),
33         do_sha512(false)
34 {
35
36         GetOpt getopt;
37         getopt.add_option("md5", do_md5, GetOpt::NO_ARG);
38         getopt.add_option("sha256", do_sha256, GetOpt::NO_ARG);
39         getopt.add_option("sha512", do_sha512, GetOpt::NO_ARG);
40         getopt.add_argument("file", files, GetOpt::REQUIRED_ARG);
41         getopt(argc, argv);
42
43         if(!do_md5 && !do_sha256 && !do_sha512)
44                 do_md5 = true;
45 }
46
47 int Checksum::main()
48 {
49         for(list<string>::const_iterator i=files.begin(); i!=files.end(); ++i)
50         {
51                 if(do_md5)
52                         process_file<Crypto::MD5>(*i);
53                 if(do_sha256)
54                         process_file<Crypto::SHA256>(*i);
55                 if(do_sha512)
56                         process_file<Crypto::SHA512>(*i);
57         }
58         return 0;
59 }
60
61 template<typename H>
62 void Checksum::process_file(const string &fn)
63 {
64         IO::BufferedFile infile(fn);
65         H hash;
66         while(1)
67         {
68                 char buffer[16384];
69                 unsigned len = infile.read(buffer, sizeof(buffer));
70                 if(!len)
71                         break;
72                 hash.update(buffer, len);
73         }
74         IO::print("%s  %s\n", hash.get_hexdigest(), fn);
75 }