std::string b64encode(InputIterator begin, InputIterator end) { unsigned char in[3], out[4]; int i, len; std::string databuf; while( begin != end ) { len = 0; for( i = 0; i < 3; i++ ) { if( begin != end ) { in[i] = static_cast<unsigned char>( *begin++ ); len++; } else { in[i] = 0; } } if( len ) { encodeblock( in, out, len ); for( i = 0; i < 4; i++ ) { databuf.push_back(out[i]); } } } return databuf; }
QString Base64Converter::convert(const QString& text) { QByteArray byte_array = text.toLocal8Bit(); const unsigned char* from_str = (const unsigned char*)byte_array.constData(); int to_str_len = (byte_array.size() + 2) / 3 * 4; unsigned char* to_str = new unsigned char[to_str_len + 1]; to_str[to_str_len] = '\0'; for(int i = 0; i<byte_array.size()/3; i++) { encodeblock( &from_str[i*3], &to_str[i*4], 3); } if (byte_array.size()%3 != 0) { encodeblock( &from_str[byte_array.size()/3*3], &to_str[byte_array.size()/3*4], byte_array.size()%3); } QString result = QString::fromLocal8Bit((char*)to_str); delete[] to_str; return result; }
int tobase64(const char* str, int len, char* buf) { int a=0, i=0; do { encodeblock(&str[i], &buf[a], min(len,3)); i+=3; a+=4; len -= 3; }while(len > 0); return a; }
/* ** encode ** ** base64 encode a stream adding padding and line breaks as per spec. */ void encode( const std::vector<unsigned char> &input, std::string &output, int linesize ) { unsigned char in[3], out[4]; int i, len, blocksout = 0; std::vector<unsigned char>::const_iterator cit = input.begin(); while( cit != input.end() ) { len = 0; for( i = 0; i < 3; i++ ) { in[i] = (unsigned char) *cit; if( cit != input.end() ) { len++; ++cit; } else { in[i] = 0; } } if( len ) { encodeblock( in, out, len ); output.append( (const char*)&out[0], (std::string::size_type) 4 ); blocksout++; } if( linesize > 0 and blocksout >= (linesize/4) || cit == input.end() ) { if( blocksout ) { output.append( std::string("\r\n") ); } blocksout = 0; } } }