Helper.cpp 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include "Helper.hpp"
  2. #include "ExceptionSystem.hpp"
  3. #include <iostream>
  4. #undef __BASE_FILE__
  5. #define __BASE_FILE__ TEXT("Helper.cpp")
  6. namespace Helper {
  7. TString Base64Encode(const std::vector<uint8_t>& bytes) {
  8. TString RetValue;
  9. DWORD pcchString = 0;
  10. if (bytes.empty())
  11. return RetValue;
  12. if (!CryptBinaryToString(bytes.data(),
  13. static_cast<DWORD>(bytes.size()),
  14. CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
  15. NULL,
  16. &pcchString))
  17. throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
  18. TEXT("CryptBinaryToString failed."));
  19. RetValue.resize(pcchString);
  20. if (!CryptBinaryToString(bytes.data(),
  21. static_cast<DWORD>(bytes.size()),
  22. CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
  23. RetValue.data(),
  24. &pcchString))
  25. throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
  26. TEXT("CryptBinaryToString failed."));
  27. while (RetValue.back() == TEXT('\x00'))
  28. RetValue.pop_back();
  29. return RetValue;
  30. }
  31. std::vector<uint8_t> Base64Decode(const TString& Base64Str) {
  32. std::vector<uint8_t> RetValue;
  33. DWORD pcbBinary = 0;
  34. if (Base64Str.empty())
  35. return RetValue;
  36. if (!CryptStringToBinary(Base64Str.c_str(),
  37. NULL,
  38. CRYPT_STRING_BASE64,
  39. NULL,
  40. &pcbBinary,
  41. NULL,
  42. NULL))
  43. throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
  44. TEXT("CryptStringToBinary failed."),
  45. TEXT("Are you sure it is a Base64 string?"));
  46. RetValue.resize(pcbBinary);
  47. if (!CryptStringToBinary(Base64Str.c_str(),
  48. NULL,
  49. CRYPT_STRING_BASE64,
  50. RetValue.data(),
  51. &pcbBinary,
  52. NULL,
  53. NULL))
  54. throw SystemException(__BASE_FILE__, __LINE__, GetLastError(),
  55. TEXT("CryptStringToBinary failed."));
  56. return RetValue;
  57. }
  58. bool ReadInt(int& RefInt, int MinVal, int MaxVal, PCTSTR Prompt, PCTSTR ErrMsg) {
  59. int t;
  60. TString s;
  61. while (true) {
  62. _tprintf_s(TEXT("%s"), Prompt);
  63. if (!std::getline(std::_tcin, s))
  64. return false;
  65. if (s.empty())
  66. continue;
  67. try {
  68. t = std::stoi(s, nullptr, 0);
  69. if (MinVal <= t && t <= MaxVal) {
  70. RefInt = t;
  71. return true;
  72. } else {
  73. throw std::invalid_argument("");
  74. }
  75. } catch (...) {
  76. _putts(ErrMsg);
  77. }
  78. }
  79. }
  80. }