C++ boost base64, 从文件读取二进制数据并base64,读取文本中的base64并解码

By | 2019年3月29日
bool Base64Encode( const string & input, string * output )
{
    typedef base64_from_binary<transform_width<string::const_iterator, 6, 8>> Base64EncodeIterator;
    stringstream result;
    try {
        copy( Base64EncodeIterator( input.begin() ), Base64EncodeIterator( input.end() ), ostream_iterator<char>( result ) );
    } catch ( ... ) {
        return false;
    }
    size_t equal_count = (3 - input.length() % 3) % 3;
    for ( size_t i = 0; i < equal_count; i++ )
    {
        result.put( '=' );
    }
    *output = result.str();
    return output->empty() == false;
}


std::string decode64(const std::string &val) {
    using namespace boost::archive::iterators;
    using It = transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>;
    return boost::algorithm::trim_right_copy_if(std::string(It(std::begin(val)), It(std::end(val))), [](char c) {
        return c == '\0';
    });
}
    ifstream fre;
    fre.open("data",ios::binary|ios::in);

    fre.seekg(0,ifstream::end);
    unsigned long long size = fre.tellg();
    fre.seekg(0);
    char *tmp = new char[size];

    fre.read(tmp,size);
    string strtmp = string(tmp);

    std::string encoded;
    std::string b;
    Base64Encode(strtmp, &encoded);
    Base64Decode(encoded, &b);

    std::cout<<encoded<<endl<<endl<<b<<endl;
    ifstream fre;
    fre.open("ssss",ios::in);
    string strtmp;
    fre >> strtmp;

    std::string encoded;
    std::string b;

    std::cout<<decode64(strtmp)<<endl;

点击量:556