md5.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #pragma once
  2. #include <util/generic/array_ref.h>
  3. #include <util/generic/strbuf.h>
  4. class IInputStream;
  5. class MD5 {
  6. public:
  7. MD5() {
  8. Init();
  9. }
  10. void Init();
  11. inline MD5& Update(const void* data, size_t len) {
  12. return Update(MakeArrayRef(static_cast<const ui8*>(data), len));
  13. }
  14. inline MD5& Update(TStringBuf data) {
  15. return Update(data.data(), data.size());
  16. }
  17. inline MD5& Update(const TArrayRef<const ui8> data) {
  18. UpdatePart(data);
  19. return *this;
  20. }
  21. void Pad();
  22. ui8* Final(ui8[16]);
  23. // buf must be char[33];
  24. char* End(char* buf);
  25. // buf must be char[25];
  26. char* End_b64(char* buf);
  27. // 8-byte xor-based mix
  28. ui64 EndHalfMix();
  29. MD5& Update(IInputStream* in);
  30. /*
  31. * Return hex-encoded md5 checksum for given file.
  32. *
  33. * Return nullptr / empty string if the file does not exist.
  34. */
  35. static char* File(const char* filename, char* buf);
  36. static TString File(const TString& filename);
  37. static char* Data(const void* data, size_t len, char* buf);
  38. static char* Data(const TArrayRef<const ui8>& data, char* buf);
  39. static TString Data(const TArrayRef<const ui8>& data);
  40. static TString Data(TStringBuf data);
  41. static char* Stream(IInputStream* in, char* buf);
  42. static TString Calc(TStringBuf data); // 32-byte hex-encoded
  43. static TString Calc(const TArrayRef<const ui8>& data); // 32-byte hex-encoded
  44. static TString CalcRaw(TStringBuf data); // 16-byte raw
  45. static TString CalcRaw(const TArrayRef<const ui8>& data); // 16-byte raw
  46. static ui64 CalcHalfMix(TStringBuf data);
  47. static ui64 CalcHalfMix(const TArrayRef<const ui8>& data);
  48. static ui64 CalcHalfMix(const char* data, size_t len);
  49. static bool IsMD5(TStringBuf data);
  50. static bool IsMD5(const TArrayRef<const ui8>& data);
  51. private:
  52. void UpdatePart(TArrayRef<const ui8> data);
  53. private:
  54. ui8 BufferSize; /* size of buffer */
  55. ui8 Buffer[64]; /* input buffer */
  56. ui32 State[4]; /* state (ABCD) */
  57. ui64 StreamSize; /* total bytes in input stream */
  58. };