cxtream  0.5.1
C++17 data pipeline with Python bindings.
base64.hpp
1 /****************************************************************************
2  * cxtream library
3  * Copyright (c) 2017, Cognexa Solutions s.r.o.
4  * Author(s) Filip Matzner
5  *
6  * This file is distributed under the MIT License.
7  * See the accompanying file LICENSE.txt for the complete license agreement.
8  ****************************************************************************/
10 
11 #ifndef CXTREAM_CORE_BASE64_HPP
12 #define CXTREAM_CORE_BASE64_HPP
13 
14 #include <boost/algorithm/string.hpp>
15 #include <boost/archive/iterators/base64_from_binary.hpp>
16 #include <boost/archive/iterators/binary_from_base64.hpp>
17 #include <boost/archive/iterators/transform_width.hpp>
18 
19 #include <vector>
20 #include <string>
21 
22 namespace cxtream {
23 
26 std::vector<std::uint8_t> base64_decode(const std::string& b64data)
27 {
28  using namespace boost::archive::iterators;
29  using It = transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>;
30 
31  // skip padding characters
32  std::size_t len = b64data.size();
33  while (len && b64data[len - 1] == '=') --len;
34 
35  return std::vector<std::uint8_t>(It(std::begin(b64data)), It(std::begin(b64data) + len));
36 }
37 
40 std::string base64_encode(const std::vector<std::uint8_t>& data)
41 {
42  using namespace boost::archive::iterators;
43  using It = base64_from_binary<transform_width<std::vector<std::uint8_t>::const_iterator, 6, 8>>;
44  std::string res(It(std::begin(data)), It(std::end(data)));
45  return res.append((3 - data.size() % 3) % 3, '=');
46 }
47 
48 } // end namespace cxtream
49 #endif
std::string base64_encode(const std::vector< std::uint8_t > &data)
Encode a vector of bytes to a base64 encoded string.
Definition: base64.hpp:40
std::vector< std::uint8_t > base64_decode(const std::string &b64data)
Decode base64 encoded string to a vector of bytes.
Definition: base64.hpp:26