comparison C++/Hash.h @ 213:1829c4266bee

Hash: hash functions
author David Demelier <markand@malikania.fr>
date Mon, 24 Mar 2014 13:54:28 +0100
parents
children 6a664378c5c4
comparison
equal deleted inserted replaced
212:35e34b0b80d4 213:1829c4266bee
1 /*
2 * Hash.h -- hash functions
3 *
4 * Copyright (c) 2014 David Demelier <markand@malikania.fr>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #ifndef _HASH_H_
20 #define _HASH_H_
21
22 /**
23 * @file Hash.h
24 * @brief Hash functions
25 */
26
27 #include <string>
28
29 /**
30 * @class Hash
31 * @brief Hash functions
32 *
33 * Provide support for MD5, SHA1, SHA256 and SHA512.
34 */
35 class Hash {
36 private:
37 template <typename Context>
38 using Init = int (*)(Context *);
39
40 template <typename Context>
41 using Update = int (*)(Context *, const void *, size_t);
42
43 template <typename Context>
44 using Final = int (*)(unsigned char *, Context *);
45
46 template <typename Context, size_t Length>
47 static std::string convert(const std::string &input,
48 Init<Context> init,
49 Update<Context> update,
50 Final<Context> finalize)
51 {
52 unsigned char digest[Length];
53 char hash[Length * 2 + 1];
54
55 Context ctx;
56 init(&ctx);
57 update(&ctx, input.c_str(), input.length());
58 finalize(digest, &ctx);
59
60 for (int i = 0; i < Length; i++)
61 sprintf(&hash[i * 2], "%02x", (unsigned int)digest[i]);
62
63 return std::string(hash);
64 }
65
66 public:
67 /**
68 * Hash using MD5.
69 *
70 * @param input the input string
71 * @return the hashed string
72 */
73 static std::string md5(const std::string &input);
74
75 /**
76 * Hash using SHA1.
77 *
78 * @param input the input string
79 * @return the hashed string
80 */
81 static std::string sha1(const std::string &input);
82
83 /**
84 * Hash using SHA256.
85 *
86 * @param input the input string
87 * @return the hashed string
88 */
89 static std::string sha256(const std::string &input);
90
91 /**
92 * Hash using SHA512.
93 *
94 * @param input the input string
95 * @return the hashed string
96 */
97 static std::string sha512(const std::string &input);
98 };
99
100 #endif // !_HASH_H_