1 /* Cumulus: Smart Filesystem Backup to Dumb Servers
3 * Copyright (C) 2012 Michael Vrable <vrable@cs.hmc.edu>
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.
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.
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.
30 static string default_algorithm;
31 static map<string, Hash *(*)()> hash_registry;
33 void Hash::Register(const std::string& name, Hash *(*constructor)())
35 printf("Registered hash algorithm %s\n", name.c_str());
36 hash_registry.insert(make_pair(name, constructor));
41 return New(default_algorithm);
44 Hash *Hash::New(const std::string& name)
46 Hash *(*constructor)() = hash_registry[name];
53 std::string Hash::hash_file(const char *filename)
56 Hash *hash = Hash::New();
57 if (hash->update_from_file(filename))
58 result = hash->digest_str();
64 bool Hash::update_from_file(const char *filename)
66 FILE *f = fopen(filename, "rb");
72 size_t bytes = fread(buf, 1, sizeof(buf), f);
86 const uint8_t *Hash::digest()
89 digest_bytes = finalize();
95 string Hash::digest_str()
97 const uint8_t *raw_digest = digest();
98 size_t len = digest_size();
99 char hexbuf[len*2 + 1];
102 for (size_t i = 0; i < len; i++) {
103 snprintf(&hexbuf[2*i], 3, "%02x", raw_digest[i]);
106 return name() + "=" + hexbuf;
109 void sha1_register();
110 void sha256_register();
116 default_algorithm = "sha224";