如何仅使用 boost 将字符串编码为 base64? [英] How do I encode a string to base64 using only boost?

查看:55
本文介绍了如何仅使用 boost 将字符串编码为 base64?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个简单的 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;

这篇关于如何仅使用 boost 将字符串编码为 base64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆