SecByteBlockSink

From Crypto++ Wiki
Jump to navigation Jump to 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>

#include "cryptlib.h"
#include "filters.h"
#include "files.h"
#include "modes.h"
#include "queue.h"
#include "hex.h"
#include "aes.h"

int main(int argc, char* argv[])
{
  using namespace CryptoPP;

  SecByteBlock key(AES::MAX_KEYLENGTH);
  SecByteBlock iv(AES::BLOCKSIZE);
  HexEncoder encoder(new FileSink(std::cout));

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

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

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

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

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

  return 0;
}

Downloads

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