Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

c++ - attempt to decode a value not in base64 char set

I am using the following code snippet to base64 encode and decode a string using Boost C++ library.

//Base64 Encode Implementation using Boost C++ library
const std::string base64_padding[] = {"", "=", "=="};

std::string X_Privet_Token_Generator::base64_encode(const std::string & s)
{
  namespace bai = boost::archive::iterators;

  std::stringstream os;

  // convert binary values to base64 characters
  typedef bai::base64_from_binary

  // retrieve 6 bit integers from a sequence of 8 bit bytes
  <bai::transform_width<const char *, 6, 8> > base64_enc; // compose all the above operations in to a new iterator

  std::copy(base64_enc(s.c_str()), base64_enc(s.c_str() + s.size()), std::ostream_iterator<char>(os));

  os << base64_padding[s.size() % 3];
  return os.str();
}

std::string X_Privet_Token_Generator::base64_decode(std::string & s)
{
  namespace bai = boost::archive::iterators;

  std::stringstream os;

  // convert binary values to base64 characters
  typedef bai::binary_from_base64

  <bai::transform_width<const char *, 8, 6> > base64_dec;

  unsigned int size = s.size();

  // Remove the padding characters, cf.
  if (size && s[size - 1] == '=')
  {
      --size;
      if (size && s[size - 1] == '=')
          --size;
  }

  if (size == 0)
      return std::string();

  LOGINFO("Hash decoded token : %s", s.c_str());
  std::copy(base64_dec(s.data()), base64_dec(s.data() + size), std::ostream_iterator<char>(os));
  std::cout<< os.str();
  return os.str();
}

Encoding works well, however, while decoding I get the following error:

terminate called after throwing an instance of boost::archive::iterators::dataflow_exception

what(): attempt to decode a value not in base64 char set

Is it one of the padded characters that is causing this issue? Am I missing something here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The padding characters '=' are part of the b64 encoded data and should not be removed before decoding. b64 is encoded in blocks of 4 character, I suspect that while decoding it reads a '' instead of an expected '=' at the end of the string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...