md5_ut.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include "md5.h"
  2. #include <library/cpp/testing/unittest/registar.h>
  3. #include <util/system/fs.h>
  4. #include <util/stream/file.h>
  5. Y_UNIT_TEST_SUITE(TMD5Test) {
  6. Y_UNIT_TEST(TestMD5) {
  7. // echo -n 'qwertyuiopqwertyuiopasdfghjklasdfghjkl' | md5sum
  8. constexpr const char* b = "qwertyuiopqwertyuiopasdfghjklasdfghjkl";
  9. MD5 r;
  10. r.Update((const unsigned char*)b, 15);
  11. r.Update((const unsigned char*)b + 15, strlen(b) - 15);
  12. char rs[33];
  13. TString s(r.End(rs));
  14. s.to_lower();
  15. UNIT_ASSERT_NO_DIFF(s, TStringBuf("3ac00dd696b966fd74deee3c35a59d8f"));
  16. TString result = r.Calc(TStringBuf(b));
  17. result.to_lower();
  18. UNIT_ASSERT_NO_DIFF(result, TStringBuf("3ac00dd696b966fd74deee3c35a59d8f"));
  19. }
  20. Y_UNIT_TEST(TestFile) {
  21. TString s = NUnitTest::RandomString(1000000, 1);
  22. const TString tmpFile = "tmp";
  23. {
  24. TFixedBufferFileOutput fo(tmpFile);
  25. fo.Write(s.data(), s.size());
  26. }
  27. char fileBuf[100];
  28. char memBuf[100];
  29. TString fileHash = MD5::File(tmpFile.data(), fileBuf);
  30. TString memoryHash = MD5::Data((const unsigned char*)s.data(), s.size(), memBuf);
  31. UNIT_ASSERT_NO_DIFF(fileHash, memoryHash);
  32. fileHash = MD5::File(tmpFile);
  33. UNIT_ASSERT_NO_DIFF(fileHash, memoryHash);
  34. NFs::Remove(tmpFile);
  35. fileHash = MD5::File(tmpFile);
  36. UNIT_ASSERT_EQUAL(fileHash.size(), 0);
  37. }
  38. Y_UNIT_TEST(TestIsMD5) {
  39. UNIT_ASSERT_EQUAL(false, MD5::IsMD5(TStringBuf()));
  40. UNIT_ASSERT_EQUAL(false, MD5::IsMD5(TStringBuf("4136ebb0e4c45d21e2b09294c75cfa0"))); // length 31
  41. UNIT_ASSERT_EQUAL(false, MD5::IsMD5(TStringBuf("4136ebb0e4c45d21e2b09294c75cfa000"))); // length 33
  42. UNIT_ASSERT_EQUAL(false, MD5::IsMD5(TStringBuf("4136ebb0e4c45d21e2b09294c75cfa0g"))); // wrong character 'g'
  43. UNIT_ASSERT_EQUAL(true, MD5::IsMD5(TStringBuf("4136EBB0E4C45D21E2B09294C75CFA08")));
  44. UNIT_ASSERT_EQUAL(true, MD5::IsMD5(TStringBuf("4136ebb0E4C45D21e2b09294C75CfA08")));
  45. UNIT_ASSERT_EQUAL(true, MD5::IsMD5(TStringBuf("4136ebb0e4c45d21e2b09294c75cfa08")));
  46. }
  47. Y_UNIT_TEST(TestMd5HalfMix) {
  48. UNIT_ASSERT_EQUAL(MD5::CalcHalfMix(""), 7203772011789518145ul);
  49. UNIT_ASSERT_EQUAL(MD5::CalcHalfMix("qwertyuiopqwertyuiopasdfghjklasdfghjkl"), 11753545595885642730ul);
  50. }
  51. }