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

前端 未结 9 1035
南方客
南方客 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条回答
  •  遥遥无期
    2020-12-04 11:22

    Another solution using boost base64 encode decode:

    const std::string base64_padding[] = {"", "==","="};
    std::string base64_encode(const std::string& s) {
      namespace bai = boost::archive::iterators;
    
      std::stringstream os;
    
      // convert binary values to base64 characters
      typedef bai::base64_from_binary
      // retrieve 6 bit integers from a sequence of 8 bit bytes
       > base64_enc; // compose all the above operations in to a new iterator
    
      std::copy(base64_enc(s.c_str()), base64_enc(s.c_str() + s.size()),
                std::ostream_iterator(os));
    
      os << base64_padding[s.size() % 3];
      return os.str();
    }
    
    std::string base64_decode(const std::string& s) {
      namespace bai = boost::archive::iterators;
    
      std::stringstream os;
    
      typedef bai::transform_width, 8, 6> base64_dec;
    
      unsigned int size = s.size();
    
      // Remove the padding characters, cf. https://svn.boost.org/trac/boost/ticket/5629
      if (size && s[size - 1] == '=') {
        --size;
        if (size && s[size - 1] == '=') --size;
      }
      if (size == 0) return std::string();
    
      std::copy(base64_dec(s.data()), base64_dec(s.data() + size),
                std::ostream_iterator(os));
    
      return os.str();
    }
    

    And here are the test cases:

        std::string t_e[TESTSET_SIZE] = {
            ""
          , "M"
          , "Ma"
          , "Man"
          , "pleasure."
          , "leasure."
          , "easure."
          , "asure."
          , "sure."
    };
    std::string t_d[TESTSET_SIZE] = {
            ""
          , "TQ=="
          , "TWE="
          , "TWFu"
          , "cGxlYXN1cmUu"
          , "bGVhc3VyZS4="
          , "ZWFzdXJlLg=="
          , "YXN1cmUu"
          , "c3VyZS4="
    };
    

    Hope this helps

提交回复
热议问题