xbase64.hpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /***************************************************************************
  2. * Copyright (c) Sylvain Corlay and Johan Mabille and Wolf Vollprecht *
  3. * Copyright (c) QuantStack *
  4. * *
  5. * Distributed under the terms of the BSD 3-Clause License. *
  6. * *
  7. * The full license is in the file LICENSE, distributed with this software. *
  8. ****************************************************************************/
  9. #ifndef XTL_BASE64_HPP
  10. #define XTL_BASE64_HPP
  11. #include <array>
  12. #include <cstddef>
  13. #include <string>
  14. #include "xsequence.hpp"
  15. namespace xtl
  16. {
  17. inline std::string base64decode(const std::string& input)
  18. {
  19. std::array<int, 256> T;
  20. T.fill(-1);
  21. for (std::size_t i = 0; i < 64; ++i)
  22. {
  23. T[std::size_t("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i])] = int(i);
  24. }
  25. std::string output;
  26. int val = 0;
  27. int valb = -8;
  28. for (char c : input)
  29. {
  30. if (T[std::size_t(c)] == -1)
  31. {
  32. break;
  33. }
  34. val = (val << 6) + T[std::size_t(c)];
  35. valb += 6;
  36. if (valb >= 0)
  37. {
  38. output.push_back(char((val >> valb) & 0xFF));
  39. valb -= 8;
  40. }
  41. }
  42. return output;
  43. }
  44. inline std::string base64encode(const std::string& input)
  45. {
  46. std::string output;
  47. int val = 0;
  48. int valb = -6;
  49. for (char sc : input)
  50. {
  51. unsigned char c = static_cast<unsigned char>(sc);
  52. val = (val << 8) + c;
  53. valb += 8;
  54. while (valb >= 0)
  55. {
  56. output.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(val >> valb) & 0x3F]);
  57. valb -= 6;
  58. }
  59. }
  60. if (valb > -6)
  61. {
  62. output.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[((val << 8) >> (valb + 8)) & 0x3F]);
  63. }
  64. while (output.size() % 4)
  65. {
  66. output.push_back('=');
  67. }
  68. return output;
  69. }
  70. }
  71. #endif