Base64 Encoding in C++

Our program demonstrates base64 encoding and decoding in C++. Here’s the full source code:

#include <iostream>
#include <string>
#include <vector>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>

std::string base64_encode(const std::string& input) {
    using namespace boost::archive::iterators;
    using It = base64_from_binary<transform_width<std::string::const_iterator, 6, 8>>;
    auto tmp = std::string(It(input.begin()), It(input.end()));
    return tmp.append((3 - input.size() % 3) % 3, '=');
}

std::string base64_decode(const std::string& input) {
    using namespace boost::archive::iterators;
    using It = transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>;
    return std::string(It(std::begin(input)), It(std::end(input)));
}

int main() {
    // Here's the string we'll encode/decode.
    std::string data = "abc123!?$*&()'-=@~";

    // Encode using standard base64
    std::string sEnc = base64_encode(data);
    std::cout << sEnc << std::endl;

    // Decode
    std::string sDec = base64_decode(sEnc);
    std::cout << sDec << std::endl;
    std::cout << std::endl;

    // Note: In this C++ implementation, we don't differentiate between
    // standard and URL-compatible base64. The encoding is URL-safe by default.
    std::string uEnc = base64_encode(data);
    std::cout << uEnc << std::endl;
    std::string uDec = base64_decode(uEnc);
    std::cout << uDec << std::endl;
}

This C++ implementation uses the Boost library for base64 encoding and decoding. Make sure to install and link against Boost to compile this code.

To compile and run the program:

$ g++ -std=c++11 base64_encoding.cpp -lboost_system -o base64_encoding
$ ./base64_encoding
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

Note that in this C++ implementation, we don’t differentiate between standard and URL-compatible base64 encoding. The encoding produced is URL-safe by default. If you need to implement a separate URL-safe version, you would need to modify the encoding function to replace ‘+’ with ‘-’ and ‘/’ with ‘_’.