如何仅使用 boost 将字符串编码为 base64?

2021-12-24 00:00:00 string base64 c++ boost

我正在尝试将一个简单的 ASCII 字符串快速编码为 base64(使用 boost::asio 的基本 HTTP 身份验证),而不是粘贴任何新的代码代码或使用任何超出 boost 的库.

I'm trying to quickly encode a simple ASCII string to base64 (Basic HTTP Authentication using boost::asio) and not paste in any new code code or use any libraries beyond boost.

简单的签名如下:string Base64Encode(const string& text);

我再次意识到该算法很简单,并且有很多库/示例可以这样做,但我正在寻找一个干净的提升示例.我找到了 boost 序列化,但没有明确的例子,也没有来自谷歌的例子.http://www.boost.org/doc/libs/1_46_1/libs/serialization/doc/dataflow.html

Again I realize the algorithm is easy and there are many libraries/examples doing this but I'm looking for a clean boost example. I found boost serialization but no clear examples there or from Google. http://www.boost.org/doc/libs/1_46_1/libs/serialization/doc/dataflow.html

如果不将实际的 base64 算法显式添加到我的代码中,这是否可行?

Is this possible without adding the actual base64 algorithm explicitly to my code?

推荐答案

我改进了您提供的链接中的示例:

I improved the example in the link you provided a little:

#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/insert_linebreaks.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/archive/iterators/ostream_iterator.hpp>
#include <sstream>
#include <string>
#include <iostream>


int main()
{
    using namespace boost::archive::iterators;

    std::string test = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce ornare ullamcorper ipsum ac gravida.";

    std::stringstream os;
    typedef 
        insert_linebreaks<         // insert line breaks every 72 characters
            base64_from_binary<    // convert binary values to base64 characters
                transform_width<   // retrieve 6 bit integers from a sequence of 8 bit bytes
                    const char *,
                    6,
                    8
                >
            > 
            ,72
        > 
        base64_text; // compose all the above operations in to a new iterator

    std::copy(
        base64_text(test.c_str()),
        base64_text(test.c_str() + test.size()),
        ostream_iterator<char>(os)
    );

    std::cout << os.str();
}

这会在控制台上打印出经过良好格式化的 base64 编码字符串,每 72 个字符有一个换行符,准备好放入电子邮件中.如果您不喜欢换行符,请继续使用:

This prints the string encoded base64 nicely formated with a line break every 72 characters onto the console, ready to be put into an email. If you don't like the linebreaks, just stay with this:

    typedef 
        base64_from_binary<
           transform_width<
                const char *,
                6,
                8
            >
        > 
        base64_text;

相关文章