12

Boost 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()));

わかった

agentid_coder.exeの0x75b1b9bcでの未処理の例外:Microsoft C ++例外:メモリ位置0x0046ed94でのboost :: archive :: iterators::dataflow_exception。

この回避策を見つけましたが、同じ結果が得られます

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

私はMSVS2008を使用しており、1.38をブーストします

4

1 に答える 1

37

残念ながら、この2つの組み合わせは、完全なbase64エンコーダー/デコーダーではありませんiterator_adaptors binary_from_base64transform_widthBase64は、24ビット(3バイト)のグループを4文字として表し、それぞれが6ビットをエンコードします。入力データがそのような3バイトグループの整数倍でない場合は、1つまたは2つのゼロバイトで埋める必要があります。追加されたパディングバイト数を示す=ために、エンコードされた文字列に1文字または2文字が追加されます。

transform_width、8ビットの2進数から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;

  // 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_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文字列を確認できます。

于 2012-06-11T00:04:23.387 に答える