区块链学习笔记前置篇之三:基于boost的BASE64编码与解码

#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 Base64Encode(const char*buff, int len)
{
    typedef boost::archive::iterators::base64_from_binary<boost::archive::iterators::transform_width<const char *, 6, 8> > Base64EncodeIterator;
    std::stringstream result;
    std::copy(Base64EncodeIterator(buff), Base64EncodeIterator(buff + len), std::ostream_iterator<char>(result));
    size_t equal_count = (3 - len % 3) % 3;
    for (size_t i = 0; i < equal_count; i++)
    {
        result.put('=');
    }

    return result.str();
}

void Base64Decode(const char *inbuff, int inlen, char *outbuff, int outsize, int *outlen)
{
    if (outsize * 4 / 3 < inlen)
    {
        *outlen = -1;
        return;
    }

    std::stringstream result;

    typedef boost::archive::iterators::transform_width<boost::archive::iterators::binary_from_base64<const char *>, 8, 6> Base64DecodeIterator;

    try
    {
        std::copy(Base64DecodeIterator(inbuff), Base64DecodeIterator(inbuff + inlen), std::ostream_iterator<char>(result));
    }
    catch (...)
    {
        return ;
    }

    std::string str = result.str();
    *outlen = str.length();
    memcpy((char *)outbuff, str.c_str(), *outlen);
    return ;
}

猜你喜欢

转载自blog.csdn.net/mumufan05/article/details/82012629