很不幸,结合两个 iterator_adaptors
binary_from_base64
和 transform_width
并不能完全成为一个base64编码/解码器。Base64将24位(3字节)的数据编码成4个字符,每个字符编码6位。如果输入数据的长度不是3字节的整数倍,则需要用一个或两个零字节进行填充。为了指示添加了多少填充字节,会在编码后的字符串末尾追加一个或两个=
字符。
transform_width
负责将8位二进制转换为6位整数,但它不会自动应用这种填充。用户必须手动完成填充操作。以下是一个简单的示例:
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/archive/iterators/insert_linebreaks.hpp>
#include <boost/archive/iterators/remove_whitespace.hpp>
#include <iostream>
#include <string>
using namespace boost::archive::iterators;
using namespace std;
int main(int argc, char **argv) {
typedef transform_width< binary_from_base64<remove_whitespace<string::const_iterator> >, 8, 6 > it_binary_t;
typedef insert_linebreaks<base64_from_binary<transform_width<string::const_iterator,6,8> >, 72 > it_base64_t;
string s;
getline(cin, s, '\n');
cout << "Your string is: '"<<s<<"'"<<endl;
unsigned int writePaddChars = (3-s.length()%3)%3;
string base64(it_base64_t(s.begin()),it_base64_t(s.end()));
base64.append(writePaddChars,'=');
cout << "Base64 representation: " << base64 << endl;
unsigned int paddChars = count(base64.begin(), base64.end(), '=');
std::replace(base64.begin(),base64.end(),'=','A');
string result(it_binary_t(base64.begin()), it_binary_t(base64.end()));
result.erase(result.end()-paddChars,result.end());
cout << "Decoded: " << result << endl;
return 0;
}
请注意,我添加了
insert_linebreaks
和
remove_whitespace
迭代器,以使base64输出格式良好,并且可以解码带有换行符的base64输入。这些是可选的。
使用需要不同填充的不同输入字符串运行:
$ ./base64example
Hello World!
Your string is: 'Hello World!'
Base64 representation: SGVsbG8gV29ybGQh
Decoded: Hello World!
$ ./base64example
Hello World!!
Your string is: 'Hello World!!'
Base64 representation: SGVsbG8gV29ybGQhIQ==
Decoded: Hello World!!
$ ./base64example
Hello World!!!
Your string is: 'Hello World!!!'
Base64 representation: SGVsbG8gV29ybGQhISE=
Decoded: Hello World!!!
你可以使用这个在线编码/解码器来检查base64字符串。