Base64.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /*
  2. base64.cpp and base64.h
  3. base64 encoding and decoding with C++.
  4. More information at
  5. https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp
  6. Version: 2.rc.03 (release candidate)
  7. Copyright (C) 2004-2017, 2020 René Nyffenegger
  8. This source code is provided 'as-is', without any express or implied
  9. warranty. In no event will the author be held liable for any damages
  10. arising from the use of this software.
  11. Permission is granted to anyone to use this software for any purpose,
  12. including commercial applications, and to alter it and redistribute it
  13. freely, subject to the following restrictions:
  14. 1. The origin of this source code must not be misrepresented; you must not
  15. claim that you wrote the original source code. If you use this source code
  16. in a product, an acknowledgment in the product documentation would be
  17. appreciated but is not required.
  18. 2. Altered source versions must be plainly marked as such, and must not be
  19. misrepresented as being the original source code.
  20. 3. This notice may not be removed or altered from any source distribution.
  21. René Nyffenegger rene.nyffenegger@adp-gmbh.ch
  22. */
  23. #include "Base64.h"
  24. //
  25. // Depending on the url parameter in base64_chars, one of
  26. // two sets of base64 characters needs to be chosen.
  27. // They differ in their last two characters.
  28. //
  29. const char* base64_chars[2] = {
  30. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  31. "abcdefghijklmnopqrstuvwxyz"
  32. "0123456789"
  33. "+/",
  34. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  35. "abcdefghijklmnopqrstuvwxyz"
  36. "0123456789"
  37. "-_"};
  38. static std::size_t pos_of_char(const unsigned char chr) {
  39. //
  40. // Return the position of chr within base64_encode()
  41. //
  42. if (chr >= 'A' && chr <= 'Z') return chr - 'A';
  43. else if (chr >= 'a' && chr <= 'z') return chr - 'a' + ('Z' - 'A') + 1;
  44. else if (chr >= '0' && chr <= '9') return chr - '0' + ('Z' - 'A') + ('z' - 'a') + 2;
  45. else if (chr == '+' || chr == '-') return 62; // Be liberal with input and accept both url ('-') and non-url ('+') base 64 characters (
  46. else if (chr == '/' || chr == '_') return 63; // Ditto for '/' and '_'
  47. throw "If input is correct, this line should never be reached.";
  48. }
  49. static std::string insert_linebreaks(std::string str, size_t distance) {
  50. //
  51. // Provided by https://github.com/JomaCorpFX, adapted by me.
  52. //
  53. if (!str.length()) {
  54. return "";
  55. }
  56. size_t pos = distance;
  57. while (pos < str.size()) {
  58. str.insert(pos, "\n");
  59. pos += distance + 1;
  60. }
  61. return str;
  62. }
  63. template <typename String, unsigned int line_length>
  64. static std::string encode_with_line_breaks(String s) {
  65. return insert_linebreaks(base64_encode(s, false), line_length);
  66. }
  67. template <typename String>
  68. static std::string encode_pem(String s) {
  69. return encode_with_line_breaks<String, 64>(s);
  70. }
  71. template <typename String>
  72. static std::string encode_mime(String s) {
  73. return encode_with_line_breaks<String, 76>(s);
  74. }
  75. template <typename String>
  76. static std::string encode(String s, bool url) {
  77. return base64_encode(reinterpret_cast<const unsigned char*>(s.data()), s.length(), url);
  78. }
  79. std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len, bool url) {
  80. unsigned int len_encoded = (in_len +2) / 3 * 4;
  81. unsigned char trailing_char = url ? '.' : '=';
  82. //
  83. // Choose set of base64 characters. They differ
  84. // for the last two positions, depending on the url
  85. // parameter.
  86. // A bool (as is the parameter url) is guaranteed
  87. // to evaluate to either 0 or 1 in C++ therfore,
  88. // the correct character set is chosen by subscripting
  89. // base64_chars with url.
  90. //
  91. const char* base64_chars_ = base64_chars[url];
  92. std::string ret;
  93. ret.reserve(len_encoded);
  94. unsigned int pos = 0;
  95. while (pos < in_len) {
  96. ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0xfc) >> 2]);
  97. if (pos+1 < in_len) {
  98. ret.push_back(base64_chars_[((bytes_to_encode[pos + 0] & 0x03) << 4) + ((bytes_to_encode[pos + 1] & 0xf0) >> 4)]);
  99. if (pos+2 < in_len) {
  100. ret.push_back(base64_chars_[((bytes_to_encode[pos + 1] & 0x0f) << 2) + ((bytes_to_encode[pos + 2] & 0xc0) >> 6)]);
  101. ret.push_back(base64_chars_[ bytes_to_encode[pos + 2] & 0x3f]);
  102. }
  103. else {
  104. ret.push_back(base64_chars_[(bytes_to_encode[pos + 1] & 0x0f) << 2]);
  105. ret.push_back(trailing_char);
  106. }
  107. }
  108. else {
  109. ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0x03) << 4]);
  110. ret.push_back(trailing_char);
  111. ret.push_back(trailing_char);
  112. }
  113. pos += 3;
  114. }
  115. return ret;
  116. }
  117. template <typename String>
  118. static std::string decode(String encoded_string, bool remove_linebreaks) {
  119. //
  120. // decode(…) is templated so that it can be used with String = const std::string&
  121. // or std::string_view (requires at least C++17)
  122. //
  123. if (remove_linebreaks) {
  124. if (! encoded_string.length() ) {
  125. return "";
  126. }
  127. std::string copy(encoded_string);
  128. size_t pos=0;
  129. while ((pos = copy.find("\n", pos)) != std::string::npos) {
  130. copy.erase(pos, 1);
  131. }
  132. return base64_decode(copy, false);
  133. }
  134. int length_of_string = encoded_string.length();
  135. if (!length_of_string) return std::string("");
  136. size_t in_len = length_of_string;
  137. size_t pos = 0;
  138. //
  139. // The approximate length (bytes) of the decoded string might be one ore
  140. // two bytes smaller, depending on the amount of trailing equal signs
  141. // in the encoded string. This approximation is needed to reserve
  142. // enough space in the string to be returned.
  143. //
  144. size_t approx_length_of_decoded_string = length_of_string / 4 * 3;
  145. std::string ret;
  146. ret.reserve(approx_length_of_decoded_string);
  147. while (pos < in_len) {
  148. unsigned int pos_of_char_1 = pos_of_char(encoded_string[pos+1] );
  149. ret.push_back( ( (pos_of_char(encoded_string[pos+0]) ) << 2 ) + ( (pos_of_char_1 & 0x30 ) >> 4));
  150. if (encoded_string[pos+2] != '=' && encoded_string[pos+2] != '.') { // accept URL-safe base 64 strings, too, so check for '.' also.
  151. unsigned int pos_of_char_2 = pos_of_char(encoded_string[pos+2] );
  152. ret.push_back( (( pos_of_char_1 & 0x0f) << 4) + (( pos_of_char_2 & 0x3c) >> 2));
  153. if (encoded_string[pos+3] != '=' && encoded_string[pos+3] != '.') {
  154. ret.push_back( ( (pos_of_char_2 & 0x03 ) << 6 ) + pos_of_char(encoded_string[pos+3]) );
  155. }
  156. }
  157. pos += 4;
  158. }
  159. return ret;
  160. }
  161. std::string base64_decode(std::string const& s, bool remove_linebreaks) {
  162. return decode(s, remove_linebreaks);
  163. }
  164. std::string base64_encode(std::string const& s, bool url) {
  165. return encode(s, url);
  166. }
  167. std::string base64_encode_pem (std::string const& s) {
  168. return encode_pem(s);
  169. }
  170. std::string base64_encode_mime(std::string const& s) {
  171. return encode_mime(s);
  172. }
  173. #if __cplusplus >= 201703L
  174. //
  175. // Interface with std::string_view rather than const std::string&
  176. // Requires C++17
  177. // Provided by Yannic Bonenberger (https://github.com/Yannic)
  178. //
  179. std::string base64_encode(std::string_view s, bool url) {
  180. return encode(s, url);
  181. }
  182. std::string base64_encode_pem(std::string_view s) {
  183. return encode_pem(s);
  184. }
  185. std::string base64_encode_mime(std::string_view s) {
  186. return encode_mime(s);
  187. }
  188. std::string base64_decode(std::string_view s, bool remove_linebreaks) {
  189. return decode(s, remove_linebreaks);
  190. }
  191. #endif // __cplusplus >= 201703L