summaryrefslogtreecommitdiffstats
path: root/src/Common/Hash.cpp
blob: 8194ffb521f656bacffcca04b3ba30a827c95cb2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * Hash.cpp
 *
 * Copyright (C) 2009 Matthias Schiffer <matthias@gamezock.de>
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "Hash.h"

#include <boost/scoped_array.hpp>

#include <mhash.h>

namespace Mad {
namespace Common {

const Hash::Hashes Hash::hashes;

Hash::Hashes::Hashes() {
  addHash("SHA256", MHASH_SHA256);
  addHash("Tiger192", MHASH_TIGER192);
  addHash("HAVAL192", MHASH_HAVAL192);
  addHash("SHA1", MHASH_SHA1);
  addHash("Tiger160", MHASH_TIGER160);
  addHash("HAVAL160", MHASH_HAVAL160);
  addHash("RIPEMD-160", MHASH_RIPEMD160);
  addHash("MD5", MHASH_MD5);
  addHash("Tiger128", MHASH_TIGER128);
  addHash("HAVAL128", MHASH_HAVAL128);
}

std::vector<boost::uint8_t> Hash::hash(const std::vector<boost::uint8_t> &in, unsigned int method) throw (Core::Exception) {
  MHASH mh;

  mh = mhash_init(static_cast<hashid>(method));
  if(mh == MHASH_FAILED)
    throw(Core::Exception(Core::Exception::NOT_AVAILABLE));

  boost::scoped_array<boost::uint8_t> inArray(new boost::uint8_t[in.size()]);
  std::copy(in.begin(), in.end(), inArray.get());

  mhash(mh, inArray.get(), in.size());

  std::size_t hashLength = mhash_get_block_size(static_cast<hashid>(method));

  boost::scoped_array<boost::uint8_t> outArray(new boost::uint8_t[hashLength]);
  mhash_deinit(mh, outArray.get());

  return std::vector<boost::uint8_t>(outArray.get(), outArray.get()+hashLength);
}

}
}