hash.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2023 Lain Bailey <[email protected]>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #include "updater.hpp"
  17. #include <util/windows/WinHandle.hpp>
  18. #include <vector>
  19. using namespace std;
  20. void HashToString(const B2Hash &in, string &out)
  21. {
  22. constexpr char alphabet[] = "0123456789abcdef";
  23. out.resize(kBlake2StrLength);
  24. for (size_t i = 0; i != kBlake2HashLength; ++i) {
  25. out[2 * i] = alphabet[(uint8_t)in[i] / 16];
  26. out[2 * i + 1] = alphabet[(uint8_t)in[i] % 16];
  27. }
  28. }
  29. void StringToHash(const string &in, B2Hash &out)
  30. {
  31. unsigned int temp;
  32. const char *str = in.c_str();
  33. for (size_t i = 0; i < kBlake2HashLength; i++) {
  34. sscanf_s(str + i * 2, "%02x", &temp);
  35. out[i] = static_cast<std::byte>(temp);
  36. }
  37. }
  38. bool CalculateFileHash(const wchar_t *path, B2Hash &hash)
  39. {
  40. static __declspec(thread) vector<BYTE> hashBuffer;
  41. blake2b_state blake2;
  42. if (blake2b_init(&blake2, kBlake2HashLength) != 0)
  43. return false;
  44. hashBuffer.resize(1048576);
  45. WinHandle handle = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
  46. if (handle == INVALID_HANDLE_VALUE)
  47. return false;
  48. for (;;) {
  49. DWORD read = 0;
  50. if (!ReadFile(handle, hashBuffer.data(), (DWORD)hashBuffer.size(), &read, nullptr))
  51. return false;
  52. if (!read)
  53. break;
  54. if (blake2b_update(&blake2, hashBuffer.data(), read) != 0)
  55. return false;
  56. }
  57. if (blake2b_final(&blake2, hash.data(), hash.size()) != 0)
  58. return false;
  59. return true;
  60. }