Base64编码原理时把3字节的二进制数据编码为4字节的文本数据,长度增加33%,
如果要编码的二进制数据不是3的倍数,会在最后剩下的1个或2个字节用\x00字节在末尾补足,然后在编码的末尾加上1或者2个=号。
所以在进行Base64进行解码时,得出得解码后得string得size有时候会比原始得string 多一个或者两个长度,使用以下代码便可以避免出现这个问题。
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <iostream>
#include <string>
#include <sstream>
//encode
string Base64Encode(const string &sInput)
{
typedef boost::archive::iterators::base64_from_binary<boost::archive::iterators::transform_width<string::const_iterator, 6, 8> > Base64EncodeIterator;
stringstream result;
copy(Base64EncodeIterator(sInput.begin()), Base64EncodeIterator(sInput.end()), ostream_iterator<char>(result));
size_t equal_count = (3 - sInput.length() % 3) % 3;
for (size_t i = 0; i < equal_count; i++)
{
result.put('=');
}
return result.str();
}
//decode
string Base64Decode(const string &sInput)
{
typedef boost::archive::iterators::transform_width<boost::archive::iterators::binary_from_base64<string::const_iterator>, 8, 6> Base64DecodeIterator;
stringstream result;
try
{
string temp = sInput;
int endIndex = temp.size() - 2;
if (temp[endIndex] == '=')
{
temp.erase(endIndex);
}
endIndex = temp.size() -1;
if (temp[endIndex] == '=')
{
temp.erase(endIndex);
}
copy(Base64DecodeIterator(temp.begin()), Base64DecodeIterator(temp.end()), ostream_iterator<char>(result));
}
catch (...)
{
return string();
}
return result.str();
}