Rework hash implementations to provide additional algorithms.
[cumulus.git] / hash.cc
1 /* Cumulus: Smart Filesystem Backup to Dumb Servers
2  *
3  * Copyright (C) 2012  Michael Vrable <vrable@cs.hmc.edu>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19
20 #include <stdio.h>
21 #include <stdint.h>
22 #include <map>
23 #include <string>
24
25 #include "hash.h"
26
27 using std::map;
28 using std::string;
29
30 static map<string, Hash *(*)()> hash_registry;
31
32 void Hash::Register(const std::string& name, Hash *(*constructor)())
33 {
34     printf("Registered hash algorithm %s\n", name.c_str());
35     hash_registry.insert(make_pair(name, constructor));
36 }
37
38 Hash *Hash::New()
39 {
40     // TODO: Make generic
41     return New("sha224");
42 }
43
44 Hash *Hash::New(const std::string& name)
45 {
46     Hash *(*constructor)() = hash_registry[name];
47     if (!constructor)
48         return NULL;
49     else
50         return constructor();
51 }
52
53 bool Hash::update_from_file(const char *filename)
54 {
55     FILE *f = fopen(filename, "rb");
56     if (f == NULL)
57         return false;
58
59     while (!feof(f)) {
60         char buf[4096];
61         size_t bytes = fread(buf, 1, sizeof(buf), f);
62
63         if (ferror(f)) {
64             fclose(f);
65             return false;
66         }
67
68         update(buf, bytes);
69     }
70
71     fclose(f);
72     return true;
73 }
74
75 const uint8_t *Hash::digest()
76 {
77     if (!digest_bytes) {
78         digest_bytes = finalize();
79     }
80
81     return digest_bytes;
82 }
83
84 string Hash::digest_str()
85 {
86     const uint8_t *raw_digest = digest();
87     size_t len = digest_size();
88     char hexbuf[len*2 + 1];
89
90     hexbuf[0] = '\0';
91     for (size_t i = 0; i < len; i++) {
92         snprintf(&hexbuf[2*i], 3, "%02x", raw_digest[i]);
93     }
94
95     return name() + "=" + hexbuf;
96 }
97
98 void sha1_register();
99 void sha256_register();
100
101 void hash_init()
102 {
103     sha1_register();
104     sha256_register();
105 }