SecByteBlockSink

From Crypto++ Wiki
Jump to: navigation, search

SecByteBlockSink allows you to use a SecByteBlock in a pipeline as a Sink. The source code is shown below, and the patch to filters.h is provided in the downloads section.

class CRYPTOPP_DLL SecByteBlockSink : public Bufferless<Sink>
{
public:
    SecByteBlockSink(SecByteBlock& sbb) : m_sbb(sbb) { }

    size_t Put2(const byte *inString, size_t length, int /*messageEnd*/, bool /*blocking*/)
    {
        if(!inString || !length) return length;

        m_sbb += SecByteBlock (inString, length);
		
        return 0;
    }

private:
    SecByteBlock& m_sbb;
};

Often times, you don't need a SecByteBlockSink. For example, a ByteQueue will work just fine and provide the higher level filter functions. Internally, a ByteQueue uses a SecByteBlock to buffer messages.

Below is an example of using a ByteQueue and the filter interfaces.

#include <iostream>
#include <string>
using namespace std;

#include "cryptlib.h"
#include "filters.h"
#include "files.h"
#include "modes.h"
#include "queue.h"
#include "hex.h"
#include "aes.h"
using namespace CryptoPP;

int main(int argc, char* argv[])
{
  byte key[AES::MAX_KEYLENGTH];
  byte iv[AES::BLOCKSIZE];
  HexEncoder encoder(new FileSink(cout));

  memset(key, 0x00, sizeof(key));
  memset(iv, 0x00, sizeof(iv));
  
  ByteQueue plain, cipher, recover;
  string str("Attack at dawn!");
  plain.Put(reinterpret_cast<const byte*>(str.data()), str.size());

  cout << "Plain text: ";
  plain.CopyTo(encoder);
  encoder.MessageEnd();
  cout << endl;
  
  /////////////////////////////////////////////////////////////
  
  CBC_Mode<AES>::Encryption enc;
  enc.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));

  StreamTransformationFilter f1(enc, new Redirector(cipher));
  plain.CopyTo(f1);
  f1.MessageEnd();
  
  cout << "Cipher text: ";
  cipher.CopyTo(encoder);
  encoder.MessageEnd();
  cout << endl;
  
  /////////////////////////////////////////////////////////////
  
  CBC_Mode<AES>::Decryption dec;
  dec.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));

  StreamTransformationFilter f2(dec, new Redirector(recover));
  cipher.CopyTo(f2);
  f2.MessageEnd();

  cout << "Recovered text: ";
  recover.CopyTo(encoder);
  encoder.MessageEnd();
  cout << endl;

  return 0;
}

Downloads

Filters.h.zip - Updated filters.h to add SecByteBlockSink class.