How do I encode a string to base64 using only boost?

前端 未结 9 1033
南方客
南方客 2020-12-04 10:53

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 bo

9条回答
  •  -上瘾入骨i
    2020-12-04 11:20

    This is another answer:

    #include 
    #include 
    #include 
    
    std::string ToBase64(const std::vector& binary)
    {
        using namespace boost::archive::iterators;
        using It = base64_from_binary::const_iterator, 6, 8>>;
        auto base64 = std::string(It(binary.begin()), It(binary.end()));
        // Add padding.
        return base64.append((3 - binary.size() % 3) % 3, '=');
    }
    
    std::vector FromBase64(const std::string& base64)
    {
        using namespace boost::archive::iterators;
        using It = transform_width, 8, 6>;
        auto binary = std::vector(It(base64.begin()), It(base64.end()));
        // Remove padding.
        auto length = base64.size();
        if(binary.size() > 2 && base64[length - 1] == '=' && base64[length - 2] == '=')
        {
            binary.erase(binary.end() - 2, binary.end());
        }
        else if(binary.size() > 1 && base64[length - 1] == '=')
        {
            binary.erase(binary.end() - 1, binary.end());
        }
        return binary;
    }
    

提交回复
热议问题