Crypto++  6.1
Free C++ class library of cryptographic schemes
simple.h
Go to the documentation of this file.
1 // simple.h - originally written and placed in the public domain by Wei Dai
2 
3 /// \file simple.h
4 /// \brief Classes providing basic library services.
5 
6 #ifndef CRYPTOPP_SIMPLE_H
7 #define CRYPTOPP_SIMPLE_H
8 
9 #include "config.h"
10 
11 #if CRYPTOPP_MSC_VERSION
12 # pragma warning(push)
13 # pragma warning(disable: 4127 4189)
14 #endif
15 
16 #include "cryptlib.h"
17 #include "misc.h"
18 
19 NAMESPACE_BEGIN(CryptoPP)
20 
21 /// \brief Base class for identifying alogorithm
22 /// \tparam BASE base class from which to derive
23 /// \tparam DERIVED class which to clone
24 template <class DERIVED, class BASE>
25 class CRYPTOPP_NO_VTABLE ClonableImpl : public BASE
26 {
27 public:
28  Clonable * Clone() const {return new DERIVED(*static_cast<const DERIVED *>(this));}
29 };
30 
31 /// \brief Base class information
32 /// \tparam BASE an Algorithm derived class
33 /// \tparam ALGORITHM_INFO an Algorithm derived class
34 /// \details AlgorithmImpl provides StaticAlgorithmName from the template parameter BASE
35 template <class BASE, class ALGORITHM_INFO=BASE>
36 class CRYPTOPP_NO_VTABLE AlgorithmImpl : public BASE
37 {
38 public:
39  /// \brief The algorithm name
40  /// \returns the algorithm name
41  /// \details StaticAlgorithmName returns the algorithm's name as a static member function.
42  /// The name is taken from information provided by BASE.
43  static std::string CRYPTOPP_API StaticAlgorithmName() {return ALGORITHM_INFO::StaticAlgorithmName();}
44  /// \brief The algorithm name
45  /// \returns the algorithm name
46  /// \details AlgorithmName returns the algorithm's name as a member function.
47  /// The name is is acquired by calling StaticAlgorithmName.
48  std::string AlgorithmName() const {return ALGORITHM_INFO::StaticAlgorithmName();}
49 };
50 
51 /// \brief Exception thrown when an invalid key length is encountered
52 class CRYPTOPP_DLL InvalidKeyLength : public InvalidArgument
53 {
54 public:
55  explicit InvalidKeyLength(const std::string &algorithm, size_t length) : InvalidArgument(algorithm + ": " + IntToString(length) + " is not a valid key length") {}
56 };
57 
58 /// \brief Exception thrown when an invalid number of rounds is encountered
59 class CRYPTOPP_DLL InvalidRounds : public InvalidArgument
60 {
61 public:
62  explicit InvalidRounds(const std::string &algorithm, unsigned int rounds) : InvalidArgument(algorithm + ": " + IntToString(rounds) + " is not a valid number of rounds") {}
63 };
64 
65 /// \brief Exception thrown when an invalid block size is encountered
66 class CRYPTOPP_DLL InvalidBlockSize : public InvalidArgument
67 {
68 public:
69  explicit InvalidBlockSize(const std::string &algorithm, size_t length) : InvalidArgument(algorithm + ": " + IntToString(length) + " is not a valid block size") {}
70 };
71 
72 /// \brief Exception thrown when an invalid personalization string length is encountered
73 class CRYPTOPP_DLL InvalidPersonalizationLength : public InvalidArgument
74 {
75 public:
76  explicit InvalidPersonalizationLength(const std::string &algorithm, size_t length) : InvalidArgument(algorithm + ": " + IntToString(length) + " is not a valid salt length") {}
77 };
78 
79 /// \brief Exception thrown when an invalid salt length is encountered
80 class CRYPTOPP_DLL InvalidSaltLength : public InvalidArgument
81 {
82 public:
83  explicit InvalidSaltLength(const std::string &algorithm, size_t length) : InvalidArgument(algorithm + ": " + IntToString(length) + " is not a valid salt length") {}
84 };
85 
86 // *****************************
87 
88 /// \brief Base class for bufferless filters
89 /// \tparam T the class or type
90 template <class T>
91 class CRYPTOPP_NO_VTABLE Bufferless : public T
92 {
93 public:
94  bool IsolatedFlush(bool hardFlush, bool blocking)
95  {CRYPTOPP_UNUSED(hardFlush); CRYPTOPP_UNUSED(blocking); return false;}
96 };
97 
98 /// \brief Base class for unflushable filters
99 /// \tparam T the class or type
100 template <class T>
101 class CRYPTOPP_NO_VTABLE Unflushable : public T
102 {
103 public:
104  bool Flush(bool completeFlush, int propagation=-1, bool blocking=true)
105  {return ChannelFlush(DEFAULT_CHANNEL, completeFlush, propagation, blocking);}
106  bool IsolatedFlush(bool hardFlush, bool blocking)
107  {CRYPTOPP_UNUSED(hardFlush); CRYPTOPP_UNUSED(blocking); CRYPTOPP_ASSERT(false); return false;}
108  bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true)
109  {
110  if (hardFlush && !InputBufferIsEmpty())
111  throw CannotFlush("Unflushable<T>: this object has buffered input that cannot be flushed");
112  else
113  {
114  BufferedTransformation *attached = this->AttachedTransformation();
115  return attached && propagation ? attached->ChannelFlush(channel, hardFlush, propagation-1, blocking) : false;
116  }
117  }
118 
119 protected:
120  virtual bool InputBufferIsEmpty() const {return false;}
121 };
122 
123 /// \brief Base class for input rejecting filters
124 /// \tparam T the class or type
125 /// \details T should be a BufferedTransformation derived class
126 template <class T>
127 class CRYPTOPP_NO_VTABLE InputRejecting : public T
128 {
129 public:
131  {InputRejected() : NotImplemented("BufferedTransformation: this object doesn't allow input") {}};
132 
133  /// \name INPUT
134  //@{
135 
136  /// \brief Input a byte array for processing
137  /// \param inString the byte array to process
138  /// \param length the size of the string, in bytes
139  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one
140  /// \param blocking specifies whether the object should block when processing input
141  /// \throws InputRejected
142  /// \returns the number of bytes that remain in the block (i.e., bytes not processed)
143  /// \details Internally, the default implementation throws InputRejected.
144  size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
145  {CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length); CRYPTOPP_UNUSED(messageEnd); CRYPTOPP_UNUSED(blocking); throw InputRejected();}
146  //@}
147 
148  /// \name SIGNALS
149  //@{
150  bool IsolatedFlush(bool hardFlush, bool blocking)
151  {CRYPTOPP_UNUSED(hardFlush); CRYPTOPP_UNUSED(blocking); return false;}
152  bool IsolatedMessageSeriesEnd(bool blocking)
153  {CRYPTOPP_UNUSED(blocking); throw InputRejected();}
154  size_t ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking)
155  {CRYPTOPP_UNUSED(channel); CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length); CRYPTOPP_UNUSED(messageEnd); CRYPTOPP_UNUSED(blocking); throw InputRejected();}
156  bool ChannelMessageSeriesEnd(const std::string& channel, int messageEnd, bool blocking)
157  {CRYPTOPP_UNUSED(channel); CRYPTOPP_UNUSED(messageEnd); CRYPTOPP_UNUSED(blocking); throw InputRejected();}
158  //@}
159 };
160 
161 /// \brief Interface for custom flush signals propagation
162 /// \tparam T BufferedTransformation derived class
163 template <class T>
164 class CRYPTOPP_NO_VTABLE CustomFlushPropagation : public T
165 {
166 public:
167  /// \name SIGNALS
168  //@{
169 
170  /// \brief Flush buffered input and/or output, with signal propagation
171  /// \param hardFlush is used to indicate whether all data should be flushed
172  /// \param propagation the number of attached transformations the Flush() signal should be passed
173  /// \param blocking specifies whether the object should block when processing input
174  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
175  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
176  /// \note Hard flushes must be used with care. It means try to process and output everything, even if
177  /// there may not be enough data to complete the action. For example, hard flushing a HexDecoder
178  /// would cause an error if you do it after inputing an odd number of hex encoded characters.
179  /// \note For some types of filters, like ZlibDecompressor, hard flushes can only
180  /// be done at "synchronization points". These synchronization points are positions in the data
181  /// stream that are created by hard flushes on the corresponding reverse filters, in this
182  /// example ZlibCompressor. This is useful when zlib compressed data is moved across a
183  /// network in packets and compression state is preserved across packets, as in the SSH2 protocol.
184  virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true) =0;
185 
186  //@}
187 
188 private:
189  bool IsolatedFlush(bool hardFlush, bool blocking)
190  {CRYPTOPP_UNUSED(hardFlush); CRYPTOPP_UNUSED(blocking); CRYPTOPP_ASSERT(false); return false;}
191 };
192 
193 /// \brief Interface for custom flush signals
194 /// \tparam T BufferedTransformation derived class
195 template <class T>
196 class CRYPTOPP_NO_VTABLE CustomSignalPropagation : public CustomFlushPropagation<T>
197 {
198 public:
199  /// \brief Initialize or reinitialize this object, with signal propagation
200  /// \param parameters a set of NameValuePairs to initialize or reinitialize this object
201  /// \param propagation the number of attached transformations the Initialize() signal should be passed
202  /// \details Initialize() is used to initialize or reinitialize an object using a variable number of
203  /// arbitrarily typed arguments. The function avoids the need for multiple constructors providing
204  /// all possible combintations of configurable parameters.
205  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
206  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
207  virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1) =0;
208 
209 private:
210  void IsolatedInitialize(const NameValuePairs &parameters)
211  {CRYPTOPP_UNUSED(parameters); CRYPTOPP_ASSERT(false);}
212 };
213 
214 /// \brief Multiple channels support for custom signal processing
215 /// \tparam T the class or type
216 /// \details T should be a BufferedTransformation derived class
217 template <class T>
218 class CRYPTOPP_NO_VTABLE Multichannel : public CustomFlushPropagation<T>
219 {
220 public:
221  bool Flush(bool hardFlush, int propagation=-1, bool blocking=true)
222  {return this->ChannelFlush(DEFAULT_CHANNEL, hardFlush, propagation, blocking);}
223 
224  /// \brief Marks the end of a series of messages, with signal propagation
225  /// \param propagation the number of attached transformations the MessageSeriesEnd() signal should be passed
226  /// \param blocking specifies whether the object should block when processing input
227  /// \details Each object that receives the signal will perform its processing, decrement
228  /// propagation, and then pass the signal on to attached transformations if the value is not 0.
229  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
230  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
231  /// \note There should be a MessageEnd() immediately before MessageSeriesEnd().
232  bool MessageSeriesEnd(int propagation=-1, bool blocking=true)
233  {return this->ChannelMessageSeriesEnd(DEFAULT_CHANNEL, propagation, blocking);}
234 
235  /// \brief Request space which can be written into by the caller
236  /// \param size the requested size of the buffer
237  /// \details The purpose of this method is to help avoid extra memory allocations.
238  /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
239  /// size is the requested size of the buffer. When the call returns, size is the size of
240  /// the array returned to the caller.
241  /// \details The base class implementation sets size to 0 and returns NULL.
242  /// \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of
243  /// an ArraySink, the pointer to the array is returned and the size is remaining size.
244  byte * CreatePutSpace(size_t &size)
245  {return this->ChannelCreatePutSpace(DEFAULT_CHANNEL, size);}
246 
247  /// \brief Input multiple bytes for processing
248  /// \param inString the byte buffer to process
249  /// \param length the size of the string, in bytes
250  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one
251  /// \param blocking specifies whether the object should block when processing input
252  /// \details Derived classes must implement Put2().
253  size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
254  {return this->ChannelPut2(DEFAULT_CHANNEL, inString, length, messageEnd, blocking);}
255 
256  /// \brief Input multiple bytes that may be modified by callee.
257  /// \param inString the byte buffer to process.
258  /// \param length the size of the string, in bytes.
259  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one.
260  /// \param blocking specifies whether the object should block when processing input.
261  /// \details Internally, PutModifiable2() calls Put2().
262  size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
263  {return this->ChannelPutModifiable2(DEFAULT_CHANNEL, inString, length, messageEnd, blocking);}
264 
265 // void ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1)
266 // {PropagateMessageSeriesEnd(propagation, channel);}
267  byte * ChannelCreatePutSpace(const std::string &channel, size_t &size)
268  {CRYPTOPP_UNUSED(channel); size = 0; return NULLPTR;}
269  bool ChannelPutModifiable(const std::string &channel, byte *inString, size_t length)
270  {this->ChannelPut(channel, inString, length); return false;}
271 
272  virtual size_t ChannelPut2(const std::string &channel, const byte *begin, size_t length, int messageEnd, bool blocking) =0;
273  size_t ChannelPutModifiable2(const std::string &channel, byte *begin, size_t length, int messageEnd, bool blocking)
274  {return ChannelPut2(channel, begin, length, messageEnd, blocking);}
275 
276  virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true) =0;
277 };
278 
279 /// \brief Provides auto signaling support
280 /// \tparam T BufferedTransformation derived class
281 template <class T>
282 class CRYPTOPP_NO_VTABLE AutoSignaling : public T
283 {
284 public:
285  /// \brief Construct an AutoSignaling
286  /// \param propagation the propagation count
287  AutoSignaling(int propagation=-1) : m_autoSignalPropagation(propagation) {}
288 
289  void SetAutoSignalPropagation(int propagation)
290  {m_autoSignalPropagation = propagation;}
291  int GetAutoSignalPropagation() const
292  {return m_autoSignalPropagation;}
293 
294 private:
295  int m_autoSignalPropagation;
296 };
297 
298 /// \brief Acts as a Source for pre-existing, static data
299 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Store : public AutoSignaling<InputRejecting<BufferedTransformation> >
300 {
301 public:
302  /// \brief Construct a Store
303  Store() : m_messageEnd(false) {}
304 
305  void IsolatedInitialize(const NameValuePairs &parameters)
306  {
307  m_messageEnd = false;
308  StoreInitialize(parameters);
309  }
310 
311  unsigned int NumberOfMessages() const {return m_messageEnd ? 0 : 1;}
312  bool GetNextMessage();
313  unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const;
314 
315 protected:
316  virtual void StoreInitialize(const NameValuePairs &parameters) =0;
317 
318  bool m_messageEnd;
319 };
320 
321 /// \brief Implementation of BufferedTransformation's attachment interface
322 /// \details Sink is a cornerstone of the Pipeline trinitiy. Data flows from
323 /// Sources, through Filters, and then terminates in Sinks. The difference
324 /// between a Source and Filter is a Source \a pumps data, while a Filter does
325 /// not. The difference between a Filter and a Sink is a Filter allows an
326 /// attached transformation, while a Sink does not.
327 /// \details A Sink doesnot produce any retrievable output.
328 /// \details See the discussion of BufferedTransformation in cryptlib.h for
329 /// more details.
330 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Sink : public BufferedTransformation
331 {
332 public:
333  size_t TransferTo2(BufferedTransformation &target, lword &transferBytes, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true)
334  {CRYPTOPP_UNUSED(target); CRYPTOPP_UNUSED(transferBytes); CRYPTOPP_UNUSED(channel); CRYPTOPP_UNUSED(blocking); transferBytes = 0; return 0;}
335  size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const
336  {CRYPTOPP_UNUSED(target); CRYPTOPP_UNUSED(begin); CRYPTOPP_UNUSED(end); CRYPTOPP_UNUSED(channel); CRYPTOPP_UNUSED(blocking); return 0;}
337 };
338 
339 /// \brief Acts as an input discarding Filter or Sink
340 /// \details The BitBucket discards all input and returns 0 to the caller
341 /// to indicate all data was processed.
342 class CRYPTOPP_DLL BitBucket : public Bufferless<Sink>
343 {
344 public:
345  std::string AlgorithmName() const {return "BitBucket";}
346  void IsolatedInitialize(const NameValuePairs &params)
347  {CRYPTOPP_UNUSED(params);}
348  size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
349  {CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length); CRYPTOPP_UNUSED(messageEnd); CRYPTOPP_UNUSED(blocking); return 0;}
350 };
351 
352 NAMESPACE_END
353 
354 #if CRYPTOPP_MSC_VERSION
355 # pragma warning(pop)
356 #endif
357 
358 #endif
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing.
Definition: simple.h:253
An invalid argument was detected.
Definition: cryptlib.h:199
Utility functions for the Crypto++ library.
Store()
Construct a Store.
Definition: simple.h:303
Base class for identifying alogorithm.
Definition: simple.h:25
Exception thrown when an invalid key length is encountered.
Definition: simple.h:52
std::string AlgorithmName() const
The algorithm name.
Definition: simple.h:48
unsigned int NumberOfMessages() const
Provides the number of meesages processed by this object.
Definition: simple.h:311
Flush(true) was called but it can&#39;t completely flush its buffers.
Definition: cryptlib.h:227
Abstract base classes that provide a uniform interface to this library.
bool Flush(bool hardFlush, int propagation=-1, bool blocking=true)
Flush buffered input and/or output, with signal propagation.
Definition: simple.h:221
void IsolatedInitialize(const NameValuePairs &params)
Initialize or reinitialize this object, without signal propagation.
Definition: simple.h:346
Library configuration file.
Acts as a Source for pre-existing, static data.
Definition: simple.h:299
Base class for input rejecting filters.
Definition: simple.h:127
virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true)
Flush buffered input and/or output on a channel.
Definition: cryptlib.cpp:464
Interface for buffered transformations.
Definition: cryptlib.h:1475
Interface for cloning objects.
Definition: cryptlib.h:560
Interface for custom flush signals propagation.
Definition: simple.h:164
Exception thrown when an invalid salt length is encountered.
Definition: simple.h:80
size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const
Copy bytes from this object to another BufferedTransformation.
Definition: simple.h:335
Exception thrown when an invalid block size is encountered.
Definition: simple.h:66
void IsolatedInitialize(const NameValuePairs &parameters)
Initialize or reinitialize this object, without signal propagation.
Definition: simple.h:305
Exception thrown when an invalid personalization string length is encountered.
Definition: simple.h:73
A method was called which was not implemented.
Definition: cryptlib.h:220
const std::string DEFAULT_CHANNEL
Default channel for BufferedTransformation.
Definition: cryptlib.h:482
Exception thrown when an invalid number of rounds is encountered.
Definition: simple.h:59
size_t TransferTo2(BufferedTransformation &target, lword &transferBytes, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true)
Transfer bytes from this object to another BufferedTransformation.
Definition: simple.h:333
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:60
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
Input a byte array for processing.
Definition: simple.h:144
size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes that may be modified by callee.
Definition: simple.h:262
const NameValuePairs g_nullNameValuePairs
An empty set of name-value pairs.
Definition: cryptlib.h:495
Base class for unflushable filters.
Definition: simple.h:101
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing.
Definition: simple.h:348
Implementation of BufferedTransformation&#39;s attachment interface.
Definition: simple.h:330
Provides auto signaling support.
Definition: simple.h:282
std::string IntToString(T value, unsigned int base=10)
Converts a value to a string.
Definition: misc.h:576
byte * CreatePutSpace(size_t &size)
Request space which can be written into by the caller.
Definition: simple.h:244
bool MessageSeriesEnd(int propagation=-1, bool blocking=true)
Marks the end of a series of messages, with signal propagation.
Definition: simple.h:232
Acts as an input discarding Filter or Sink.
Definition: simple.h:342
Crypto++ library namespace.
std::string AlgorithmName() const
Provides the name of this algorithm.
Definition: simple.h:345
Multiple channels support for custom signal processing.
Definition: simple.h:218
Interface for custom flush signals.
Definition: simple.h:196
AutoSignaling(int propagation=-1)
Construct an AutoSignaling.
Definition: simple.h:287
Base class for bufferless filters.
Definition: simple.h:91
Interface for retrieving values given their names.
Definition: cryptlib.h:290
Base class information.
Definition: simple.h:36