md5.h 2.0 KB

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