使用升压抛出异常Base64编码(Base64 encode using boost throw e

2019-06-24 07:07发布

我试图用升压的base64编码器,我发现了一个例子,但我得到了和异常

typedef 
transform_width< binary_from_base64<std::string::const_iterator>, 8, 6 > it_binary_t

一个我用

std::string b64E(it_binary_t(Encrip.begin()), it_binary_t(Encrip.end()));

我知道了

在0x75b1b9bc未处理异常agentid_coder.exe:微软C ++异常:提高::档案::迭代器:: dataflow_exception内存位置0x0046ed94 ..

我发现这个解决办法,但我得到了相同的结果

 string dec( 
        it_binary_t(Encrip.begin()), 
        it_binary_t(Encrip.begin() + Encrip.length() - 1) 
        ); 

我使用MSVS2008和提升1.38

Answer 1:

不幸的是,两者的结合iterator_adaptors binary_from_base64transform_width不是一个完整的base64编码器/解码器。 BASE64表示的24位(3个字节)为4个字符,其中的每个编码6位数据组。 如果输入数据不是这样的3个字节组的整数倍它必须用一个或两个零字节填充。 以指示许多填充字节是如何加入,一个或两个=字符被附加到已编码的字符串。

transform_width ,负责8位二进制6位整数转换不会自动将此填充,它具有DO用户来完成。 一个简单的例子:

#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;

  // Encode
  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;

  // Decode
  unsigned int paddChars = count(base64.begin(), base64.end(), '=');
  std::replace(base64.begin(),base64.end(),'=','A'); // replace '=' by base64 encoding of '\0'
  string result(it_binary_t(base64.begin()), it_binary_t(base64.end())); // decode
  result.erase(result.end()-paddChars,result.end());  // erase padding '\0' characters
  cout << "Decoded: " << result << endl;
  return 0;
}

请注意,我说的insert_linebreaksremove_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字符串与此线上编码器/解码器 。



文章来源: Base64 encode using boost throw exception