All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
MD5.h
1 // Copyright eeGeo Ltd (2012-2014), All Rights Reserved
2 
3 #ifndef BZF_MD5_H
4 #define BZF_MD5_H
5 
6 #include <cstring>
7 #include <iostream>
8 
9 namespace Eegeo
10 {
11  namespace Helpers
12  {
13  // a small class for calculating MD5 hashes of strings or byte arrays
14  // it is not meant to be fast or secure
15  //
16  // usage: 1) feed it blocks of uchars with update()
17  // 2) finalize()
18  // 3) get hexdigest() string
19  // or
20  // MD5(std::string).hexdigest()
21  //
22  // assumes that char is 8 bit and int is 32 bit
23  class MD5
24  {
25  public:
26  typedef unsigned int size_type; // must be 32bit
27 
28  MD5();
29  MD5(const std::string& text);
30  void update(const unsigned char *buf, size_type length);
31  void update(const char *buf, size_type length);
32  MD5& finalize();
33  std::string hexdigest() const;
34  friend std::ostream& operator<<(std::ostream&, MD5 md5);
35 
36  private:
37  void init();
38  typedef unsigned char uint1; // 8bit
39  typedef unsigned int uint4; // 32bit
40  enum {blocksize = 64}; // VC6 won't eat a const static int here
41 
42  void transform(const uint1 block[blocksize]);
43  static void decode(uint4 output[], const uint1 input[], size_type len);
44  static void encode(uint1 output[], const uint4 input[], size_type len);
45 
46  bool finalized;
47  uint1 buffer[blocksize]; // bytes that didn't fit in last 64 byte chunk
48  uint4 count[2]; // 64bit counter for number of bits (lo, hi)
49  uint4 state[4]; // digest so far
50  uint1 digest[16]; // the result
51 
52  // low level logic operations
53  static inline uint4 F(uint4 x, uint4 y, uint4 z);
54  static inline uint4 G(uint4 x, uint4 y, uint4 z);
55  static inline uint4 H(uint4 x, uint4 y, uint4 z);
56  static inline uint4 I(uint4 x, uint4 y, uint4 z);
57  static inline uint4 rotate_left(uint4 x, int n);
58  static inline void FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac);
59  static inline void GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac);
60  static inline void HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac);
61  static inline void II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac);
62  };
63 
64  std::string md5(const std::string str);
65  }
66 }
67 
68 #endif