Base64.hpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #pragma once
  2. #include <Exception.hpp>
  3. #include <ExceptionWin32.hpp>
  4. #include <xstring.hpp>
  5. #include <bytearray.hpp>
  6. #include <wincrypt.h>
  7. #pragma comment(lib, "Crypt32")
  8. #undef NKG_CURRENT_SOURCE_FILE
  9. #undef NKG_CURRENT_SOURCE_LINE
  10. #define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-keygen\\Base64.hpp")
  11. #define NKG_CURRENT_SOURCE_LINE() __LINE__
  12. namespace nkg {
  13. std::xstring Base64Encode(const std::bytearray& Bytes) {
  14. if (Bytes.empty()) {
  15. return std::xstring();
  16. } else {
  17. DWORD cchBase64String = 0;
  18. std::xstring Base64String;
  19. auto bResult = CryptBinaryToString(
  20. Bytes.data(),
  21. static_cast<DWORD>(Bytes.size()),
  22. CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
  23. NULL,
  24. &cchBase64String
  25. );
  26. if (bResult == FALSE) {
  27. throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CryptBinaryToString failed."));
  28. }
  29. Base64String.resize(cchBase64String - 1);
  30. bResult = CryptBinaryToString(
  31. Bytes.data(),
  32. static_cast<DWORD>(Bytes.size()),
  33. CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
  34. Base64String.data(),
  35. &cchBase64String
  36. );
  37. if (bResult == FALSE) {
  38. throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CryptBinaryToString failed."));
  39. }
  40. return Base64String;
  41. }
  42. }
  43. std::bytearray Base64Decode(const std::xstring& Base64String) {
  44. if (Base64String.empty()) {
  45. return std::bytearray();
  46. } else {
  47. DWORD cbBytes = 0;
  48. std::bytearray Bytes;
  49. auto bResult = CryptStringToBinary(
  50. Base64String.c_str(),
  51. NULL,
  52. CRYPT_STRING_BASE64,
  53. NULL,
  54. &cbBytes,
  55. NULL,
  56. NULL
  57. );
  58. if (bResult == FALSE) {
  59. throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CryptStringToBinary failed."))
  60. .AddHint(TEXT("Are you sure it is a Base64 string?"));
  61. }
  62. Bytes.resize(cbBytes);
  63. bResult = CryptStringToBinary(
  64. Base64String.c_str(),
  65. NULL,
  66. CRYPT_STRING_BASE64,
  67. Bytes.data(),
  68. &cbBytes,
  69. NULL,
  70. NULL
  71. );
  72. if (bResult == FALSE) {
  73. throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CryptStringToBinary failed."));
  74. }
  75. return Bytes;
  76. }
  77. }
  78. }