From Crypto++ Wiki
Jump to navigation Jump to search
#include <cryptopp/filters.h>

A StringSink serves as a destination for string data in the pipelining paradigm. The data can be binary or ASCII.

The StringSink takes a reference to a string. Because a reference is taken, the StringSink doe not own output, and therefore will not destroy output. See ownership for more details.

A StringSink is a specialization of StringSinkTemplate and declared in filters.h as:

typedef StringSinkTemplate<std::string> StringSink;


StringSink(string &output)

output is the string to store the data. The sink can store binary or ASCII data in the string.


The following example demonstrates creation of a StringSink.

string s;
StringSink sink( s );

The following example demonstrates reading a file using a FileSource, and placing the contents of the file in a string. This is known as pipelining.

string s;
FileSource file( filename, true, new StringSink( s ) );

cout << s << endl;

true indicates the FileSource should porpagate to all filters in the chain. A slightly more complicated example of pipelining is below. Before the FileSource is placed in the string, it is hex encoded.

string s;
FileSource( filename, true, new HexEncoder( new StringSink( s ) ) );

cout << s << endl;

From above, note that the HexEncoder and StringSink created with new do not require explicit destruction - the FileSource will call delete on the HexEncoder, which in turns calls delete on the StringSink when it (the FileSource) is destroyed.

byte data[] = { 0x00, 0x01, 0x02, 0x03 };
string sink;

HexEncoder encoder;
encoder.Attach( new StringSink( sink ) );
encoder.Put( data, sizeof( data ) );

cout << sink << endl;

At times, Crypto++ will require a reference to a BufferedTransformation object. For example, when saving a key to storage. To accomodate, StringSink offers Ref:

AutoSeededRandomPool rng;

// Generate Private Key
DSA::PrivateKey PrivateKey;
PrivateKey.GenerateRandomWithKeySize(rng, 1024);

string encodedPrivateKey;

// DER Encode Keys (PKCS #8)
PrivateKey.Save( StringSink(encodedPrivateKey).Ref() );