Crypto++  5.6.5
Free C++ class library of cryptographic schemes
strciphr.h
Go to the documentation of this file.
1 // strciphr.h - originally written and placed in the public domain by Wei Dai
2 
3 /// \file strciphr.h
4 /// \brief Classes for implementing stream ciphers
5 /// \details This file contains helper classes for implementing stream ciphers.
6 /// All this infrastructure may look very complex compared to what's in Crypto++ 4.x,
7 /// but stream ciphers implementations now support a lot of new functionality,
8 /// including better performance (minimizing copying), resetting of keys and IVs, and methods to
9 /// query which features are supported by a cipher.
10 /// \details Here's an explanation of these classes. The word "policy" is used here to mean a class with a
11 /// set of methods that must be implemented by individual stream cipher implementations.
12 /// This is usually much simpler than the full stream cipher API, which is implemented by
13 /// either AdditiveCipherTemplate or CFB_CipherTemplate using the policy. So for example, an
14 /// implementation of SEAL only needs to implement the AdditiveCipherAbstractPolicy interface
15 /// (since it's an additive cipher, i.e., it xors a keystream into the plaintext).
16 /// See this line in seal.h:
17 /// <pre>
18 /// typedef SymmetricCipherFinal<ConcretePolicyHolder<SEAL_Policy<B>, AdditiveCipherTemplate<> > > Encryption;
19 /// </pre>
20 /// \details AdditiveCipherTemplate and CFB_CipherTemplate are designed so that they don't need
21 /// to take a policy class as a template parameter (although this is allowed), so that
22 /// their code is not duplicated for each new cipher. Instead they each
23 /// get a reference to an abstract policy interface by calling AccessPolicy() on itself, so
24 /// AccessPolicy() must be overridden to return the actual policy reference. This is done
25 /// by the ConceretePolicyHolder class. Finally, SymmetricCipherFinal implements the constructors and
26 /// other functions that must be implemented by the most derived class.
27 
28 #ifndef CRYPTOPP_STRCIPHR_H
29 #define CRYPTOPP_STRCIPHR_H
30 
31 #include "config.h"
32 
33 #if CRYPTOPP_MSC_VERSION
34 # pragma warning(push)
35 # pragma warning(disable: 4127 4189 4231 4275)
36 #endif
37 
38 #include "cryptlib.h"
39 #include "seckey.h"
40 #include "secblock.h"
41 #include "argnames.h"
42 
43 NAMESPACE_BEGIN(CryptoPP)
44 
45 /// \brief Access a stream cipher policy object
46 /// \tparam POLICY_INTERFACE class implementing AbstractPolicyHolder
47 /// \tparam BASE class or type to use as a base class
48 template <class POLICY_INTERFACE, class BASE = Empty>
49 class CRYPTOPP_NO_VTABLE AbstractPolicyHolder : public BASE
50 {
51 public:
52  typedef POLICY_INTERFACE PolicyInterface;
53  virtual ~AbstractPolicyHolder() {}
54 
55 protected:
56  virtual const POLICY_INTERFACE & GetPolicy() const =0;
57  virtual POLICY_INTERFACE & AccessPolicy() =0;
58 };
59 
60 /// \brief Stream cipher policy object
61 /// \tparam POLICY class implementing AbstractPolicyHolder
62 /// \tparam BASE class or type to use as a base class
63 template <class POLICY, class BASE, class POLICY_INTERFACE = typename BASE::PolicyInterface>
64 class ConcretePolicyHolder : public BASE, protected POLICY
65 {
66 public:
67  virtual ~ConcretePolicyHolder() {}
68 protected:
69  const POLICY_INTERFACE & GetPolicy() const {return *this;}
70  POLICY_INTERFACE & AccessPolicy() {return *this;}
71 };
72 
73 /// \brief Keystream operation flags
74 /// \sa AdditiveCipherAbstractPolicy::GetBytesPerIteration(), AdditiveCipherAbstractPolicy::GetOptimalBlockSize()
75 /// and AdditiveCipherAbstractPolicy::GetAlignment()
77  /// \brief Output buffer is aligned
79  /// \brief Input buffer is aligned
81  /// \brief Input buffer is NULL
83 };
84 
85 /// \brief Keystream operation flags
86 /// \sa AdditiveCipherAbstractPolicy::GetBytesPerIteration(), AdditiveCipherAbstractPolicy::GetOptimalBlockSize()
87 /// and AdditiveCipherAbstractPolicy::GetAlignment()
89  /// \brief Wirte the keystream to the output buffer, input is NULL
91  /// \brief Wirte the keystream to the aligned output buffer, input is NULL
93  /// \brief XOR the input buffer and keystream, write to the output buffer
95  /// \brief XOR the aligned input buffer and keystream, write to the output buffer
97  /// \brief XOR the input buffer and keystream, write to the aligned output buffer
99  /// \brief XOR the aligned input buffer and keystream, write to the aligned output buffer
101 
102 /// \brief Policy object for additive stream ciphers
103 struct CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AdditiveCipherAbstractPolicy
104 {
105  virtual ~AdditiveCipherAbstractPolicy() {}
106 
107  /// \brief Provides data alignment requirements
108  /// \returns data alignment requirements, in bytes
109  /// \details Internally, the default implementation returns 1. If the stream cipher is implemented
110  /// using an SSE2 ASM or intrinsics, then the value returned is usually 16.
111  virtual unsigned int GetAlignment() const {return 1;}
112 
113  /// \brief Provides number of bytes operated upon during an iteration
114  /// \returns bytes operated upon during an iteration, in bytes
115  /// \sa GetOptimalBlockSize()
116  virtual unsigned int GetBytesPerIteration() const =0;
117 
118  /// \brief Provides number of ideal bytes to process
119  /// \returns the ideal number of bytes to process
120  /// \details Internally, the default implementation returns GetBytesPerIteration()
121  /// \sa GetBytesPerIteration()
122  virtual unsigned int GetOptimalBlockSize() const {return GetBytesPerIteration();}
123 
124  /// \brief Provides buffer size based on iterations
125  /// \returns the buffer size based on iterations, in bytes
126  virtual unsigned int GetIterationsToBuffer() const =0;
127 
128  /// \brief Generate the keystream
129  /// \param keystream the key stream
130  /// \param iterationCount the number of iterations to generate the key stream
131  /// \sa CanOperateKeystream(), OperateKeystream(), WriteKeystream()
132  virtual void WriteKeystream(byte *keystream, size_t iterationCount)
133  {OperateKeystream(KeystreamOperation(INPUT_NULL | (KeystreamOperationFlags)IsAlignedOn(keystream, GetAlignment())), keystream, NULLPTR, iterationCount);}
134 
135  /// \brief Flag indicating
136  /// \returns true if the stream can be generated independent of the transformation input, false otherwise
137  /// \sa CanOperateKeystream(), OperateKeystream(), WriteKeystream()
138  virtual bool CanOperateKeystream() const {return false;}
139 
140  /// \brief Operates the keystream
141  /// \param operation the operation with additional flags
142  /// \param output the output buffer
143  /// \param input the input buffer
144  /// \param iterationCount the number of iterations to perform on the input
145  /// \details OperateKeystream() will attempt to operate upon GetOptimalBlockSize() buffer,
146  /// which will be derived from GetBytesPerIteration().
147  /// \sa CanOperateKeystream(), OperateKeystream(), WriteKeystream(), KeystreamOperation()
148  virtual void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount)
149  {CRYPTOPP_UNUSED(operation); CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(iterationCount); CRYPTOPP_ASSERT(false);}
150 
151  /// \brief Key the cipher
152  /// \param params set of NameValuePairs use to initialize this object
153  /// \param key a byte array used to key the cipher
154  /// \param length the size of the key array
155  virtual void CipherSetKey(const NameValuePairs &params, const byte *key, size_t length) =0;
156 
157  /// \brief Resynchronize the cipher
158  /// \param keystreamBuffer the keystream buffer
159  /// \param iv a byte array used to resynchronize the cipher
160  /// \param length the size of the IV array
161  virtual void CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length)
162  {CRYPTOPP_UNUSED(keystreamBuffer); CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(length); throw NotImplemented("SimpleKeyingInterface: this object doesn't support resynchronization");}
163 
164  /// \brief Flag indicating random access
165  /// \returns true if the cipher is seekable, false otherwise
166  /// \sa SeekToIteration()
167  virtual bool CipherIsRandomAccess() const =0;
168 
169  /// \brief Seeks to a random position in the stream
170  /// \sa CipherIsRandomAccess()
171  virtual void SeekToIteration(lword iterationCount)
172  {CRYPTOPP_UNUSED(iterationCount); CRYPTOPP_ASSERT(!CipherIsRandomAccess()); throw NotImplemented("StreamTransformation: this object doesn't support random access");}
173 };
174 
175 /// \brief Base class for additive stream ciphers
176 /// \tparam WT word type
177 /// \tparam W count of words
178 /// \tparam X bytes per iteration count
179 /// \tparam BASE AdditiveCipherAbstractPolicy derived base class
180 template <typename WT, unsigned int W, unsigned int X = 1, class BASE = AdditiveCipherAbstractPolicy>
181 struct CRYPTOPP_NO_VTABLE AdditiveCipherConcretePolicy : public BASE
182 {
183  typedef WT WordType;
184  CRYPTOPP_CONSTANT(BYTES_PER_ITERATION = sizeof(WordType) * W)
185 
186 #if !(CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X64)
187  /// \brief Provides data alignment requirements
188  /// \returns data alignment requirements, in bytes
189  /// \details Internally, the default implementation returns 1. If the stream cipher is implemented
190  /// using an SSE2 ASM or intrinsics, then the value returned is usually 16.
191  unsigned int GetAlignment() const {return GetAlignmentOf<WordType>();}
192 #endif
193 
194  /// \brief Provides number of bytes operated upon during an iteration
195  /// \returns bytes operated upon during an iteration, in bytes
196  /// \sa GetOptimalBlockSize()
197  unsigned int GetBytesPerIteration() const {return BYTES_PER_ITERATION;}
198 
199  /// \brief Provides buffer size based on iterations
200  /// \returns the buffer size based on iterations, in bytes
201  unsigned int GetIterationsToBuffer() const {return X;}
202 
203  /// \brief Flag indicating
204  /// \returns true if the stream can be generated independent of the transformation input, false otherwise
205  /// \sa CanOperateKeystream(), OperateKeystream(), WriteKeystream()
206  bool CanOperateKeystream() const {return true;}
207 
208  /// \brief Operates the keystream
209  /// \param operation the operation with additional flags
210  /// \param output the output buffer
211  /// \param input the input buffer
212  /// \param iterationCount the number of iterations to perform on the input
213  /// \details OperateKeystream() will attempt to operate upon GetOptimalBlockSize() buffer,
214  /// which will be derived from GetBytesPerIteration().
215  /// \sa CanOperateKeystream(), OperateKeystream(), WriteKeystream(), KeystreamOperation()
216  virtual void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount) =0;
217 };
218 
219 /// \brief Helper macro to implement OperateKeystream
220 #define CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, b, i, a) \
221  PutWord(bool(x & OUTPUT_ALIGNED), b, output+i*sizeof(WordType), (x & INPUT_NULL) ? (a) : (a) ^ GetWord<WordType>(bool(x & INPUT_ALIGNED), b, input+i*sizeof(WordType)));
222 
223 /// \brief Helper macro to implement OperateKeystream
224 #define CRYPTOPP_KEYSTREAM_OUTPUT_XMM(x, i, a) {\
225  __m128i t = (x & INPUT_NULL) ? a : _mm_xor_si128(a, (x & INPUT_ALIGNED) ? _mm_load_si128((__m128i *)input+i) : _mm_loadu_si128((__m128i *)input+i));\
226  if (x & OUTPUT_ALIGNED) _mm_store_si128((__m128i *)output+i, t);\
227  else _mm_storeu_si128((__m128i *)output+i, t);}
228 
229 /// \brief Helper macro to implement OperateKeystream
230 #define CRYPTOPP_KEYSTREAM_OUTPUT_SWITCH(x, y) \
231  switch (operation) \
232  { \
233  case WRITE_KEYSTREAM: \
234  x(WRITE_KEYSTREAM) \
235  break; \
236  case XOR_KEYSTREAM: \
237  x(XOR_KEYSTREAM) \
238  input += y; \
239  break; \
240  case XOR_KEYSTREAM_INPUT_ALIGNED: \
241  x(XOR_KEYSTREAM_INPUT_ALIGNED) \
242  input += y; \
243  break; \
244  case XOR_KEYSTREAM_OUTPUT_ALIGNED: \
245  x(XOR_KEYSTREAM_OUTPUT_ALIGNED) \
246  input += y; \
247  break; \
248  case WRITE_KEYSTREAM_ALIGNED: \
249  x(WRITE_KEYSTREAM_ALIGNED) \
250  break; \
251  case XOR_KEYSTREAM_BOTH_ALIGNED: \
252  x(XOR_KEYSTREAM_BOTH_ALIGNED) \
253  input += y; \
254  break; \
255  } \
256  output += y;
257 
258 /// \brief Base class for additive stream ciphers with SymmetricCipher interface
259 /// \tparam BASE AbstractPolicyHolder base class
260 template <class BASE = AbstractPolicyHolder<AdditiveCipherAbstractPolicy, SymmetricCipher> >
261 class CRYPTOPP_NO_VTABLE AdditiveCipherTemplate : public BASE, public RandomNumberGenerator
262 {
263 public:
264  virtual ~AdditiveCipherTemplate() {}
265 
266  /// \brief Generate random array of bytes
267  /// \param output the byte buffer
268  /// \param size the length of the buffer, in bytes
269  /// \details All generated values are uniformly distributed over the range specified within the
270  /// the constraints of a particular generator.
271  void GenerateBlock(byte *output, size_t size);
272 
273  /// \brief Apply keystream to data
274  /// \param outString a buffer to write the transformed data
275  /// \param inString a buffer to read the data
276  /// \param length the size fo the buffers, in bytes
277  /// \details This is the primary method to operate a stream cipher. For example:
278  /// <pre>
279  /// size_t size = 30;
280  /// byte plain[size] = "Do or do not; there is no try";
281  /// byte cipher[size];
282  /// ...
283  /// ChaCha20 chacha(key, keySize);
284  /// chacha.ProcessData(cipher, plain, size);
285  /// </pre>
286  void ProcessData(byte *outString, const byte *inString, size_t length);
287 
288  /// \brief Resynchronize the cipher
289  /// \param iv a byte array used to resynchronize the cipher
290  /// \param length the size of the IV array
291  void Resynchronize(const byte *iv, int length=-1);
292 
293  /// \brief Provides number of ideal bytes to process
294  /// \returns the ideal number of bytes to process
295  /// \details Internally, the default implementation returns GetBytesPerIteration()
296  /// \sa GetBytesPerIteration() and GetOptimalNextBlockSize()
297  unsigned int OptimalBlockSize() const {return this->GetPolicy().GetOptimalBlockSize();}
298 
299  /// \brief Provides number of ideal bytes to process
300  /// \returns the ideal number of bytes to process
301  /// \details Internally, the default implementation returns remaining unprocessed bytes
302  /// \sa GetBytesPerIteration() and OptimalBlockSize()
303  unsigned int GetOptimalNextBlockSize() const {return (unsigned int)this->m_leftOver;}
304 
305  /// \brief Provides number of ideal data alignment
306  /// \returns the ideal data alignment, in bytes
307  /// \sa GetAlignment() and OptimalBlockSize()
308  unsigned int OptimalDataAlignment() const {return this->GetPolicy().GetAlignment();}
309 
310  /// \brief Determines if the cipher is self inverting
311  /// \returns true if the stream cipher is self inverting, false otherwise
312  bool IsSelfInverting() const {return true;}
313 
314  /// \brief Determines if the cipher is a forward transformation
315  /// \returns true if the stream cipher is a forward transformation, false otherwise
316  bool IsForwardTransformation() const {return true;}
317 
318  /// \brief Flag indicating random access
319  /// \returns true if the cipher is seekable, false otherwise
320  /// \sa Seek()
321  bool IsRandomAccess() const {return this->GetPolicy().CipherIsRandomAccess();}
322 
323  /// \brief Seeks to a random position in the stream
324  /// \param position the absolute position in the stream
325  /// \sa IsRandomAccess()
326  void Seek(lword position);
327 
328  typedef typename BASE::PolicyInterface PolicyInterface;
329 
330 protected:
331  void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params);
332 
333  unsigned int GetBufferByteSize(const PolicyInterface &policy) const {return policy.GetBytesPerIteration() * policy.GetIterationsToBuffer();}
334 
335  inline byte * KeystreamBufferBegin() {return this->m_buffer.data();}
336  inline byte * KeystreamBufferEnd() {return (this->m_buffer.data() + this->m_buffer.size());}
337 
338  SecByteBlock m_buffer;
339  size_t m_leftOver;
340 };
341 
342 /// \brief Policy object for feeback based stream ciphers
343 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CFB_CipherAbstractPolicy
344 {
345 public:
346  virtual ~CFB_CipherAbstractPolicy() {}
347 
348  /// \brief Provides data alignment requirements
349  /// \returns data alignment requirements, in bytes
350  /// \details Internally, the default implementation returns 1. If the stream cipher is implemented
351  /// using an SSE2 ASM or intrinsics, then the value returned is usually 16.
352  virtual unsigned int GetAlignment() const =0;
353 
354  /// \brief Provides number of bytes operated upon during an iteration
355  /// \returns bytes operated upon during an iteration, in bytes
356  /// \sa GetOptimalBlockSize()
357  virtual unsigned int GetBytesPerIteration() const =0;
358 
359  /// \brief Access the feedback register
360  /// \returns pointer to the first byte of the feedback register
361  virtual byte * GetRegisterBegin() =0;
362 
363  /// \brief TODO
364  virtual void TransformRegister() =0;
365 
366  /// \brief Flag indicating iteration support
367  /// \returns true if the cipher supports iteration, false otherwise
368  virtual bool CanIterate() const {return false;}
369 
370  /// \brief Iterate the cipher
371  /// \param output the output buffer
372  /// \param input the input buffer
373  /// \param dir the direction of the cipher
374  /// \param iterationCount the number of iterations to perform on the input
375  /// \sa IsSelfInverting() and IsForwardTransformation()
376  virtual void Iterate(byte *output, const byte *input, CipherDir dir, size_t iterationCount)
377  {CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(dir); CRYPTOPP_UNUSED(iterationCount);
378  CRYPTOPP_ASSERT(false); /*throw 0;*/ throw Exception(Exception::OTHER_ERROR, "SimpleKeyingInterface: unexpected error");}
379 
380  /// \brief Key the cipher
381  /// \param params set of NameValuePairs use to initialize this object
382  /// \param key a byte array used to key the cipher
383  /// \param length the size of the key array
384  virtual void CipherSetKey(const NameValuePairs &params, const byte *key, size_t length) =0;
385 
386  /// \brief Resynchronize the cipher
387  /// \param iv a byte array used to resynchronize the cipher
388  /// \param length the size of the IV array
389  virtual void CipherResynchronize(const byte *iv, size_t length)
390  {CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(length); throw NotImplemented("SimpleKeyingInterface: this object doesn't support resynchronization");}
391 };
392 
393 /// \brief Base class for feedback based stream ciphers
394 /// \tparam WT word type
395 /// \tparam W count of words
396 /// \tparam BASE CFB_CipherAbstractPolicy derived base class
397 template <typename WT, unsigned int W, class BASE = CFB_CipherAbstractPolicy>
398 struct CRYPTOPP_NO_VTABLE CFB_CipherConcretePolicy : public BASE
399 {
400  typedef WT WordType;
401 
402  /// \brief Provides data alignment requirements
403  /// \returns data alignment requirements, in bytes
404  /// \details Internally, the default implementation returns 1. If the stream cipher is implemented
405  /// using an SSE2 ASM or intrinsics, then the value returned is usually 16.
406  unsigned int GetAlignment() const {return sizeof(WordType);}
407 
408  /// \brief Provides number of bytes operated upon during an iteration
409  /// \returns bytes operated upon during an iteration, in bytes
410  /// \sa GetOptimalBlockSize()
411  unsigned int GetBytesPerIteration() const {return sizeof(WordType) * W;}
412 
413  /// \brief Flag indicating iteration support
414  /// \returns true if the cipher supports iteration, false otherwise
415  bool CanIterate() const {return true;}
416 
417  /// \brief Perform one iteration in the forward direction
418  void TransformRegister() {this->Iterate(NULLPTR, NULLPTR, ENCRYPTION, 1);}
419 
420  /// \brief Provides alternate access to a feedback register
421  /// \tparam B enumeration indicating endianness
422  /// \details RegisterOutput() provides alternate access to the feedback register. The
423  /// enumeration B is BigEndian or LittleEndian. Repeatedly applying operator()
424  /// results in advancing in the register.
425  template <class B>
427  {
428  RegisterOutput(byte *output, const byte *input, CipherDir dir)
429  : m_output(output), m_input(input), m_dir(dir) {}
430 
431  /// \brief XOR feedback register with data
432  /// \param registerWord data represented as a word type
433  /// \returns reference to the next feedback register word
434  inline RegisterOutput& operator()(WordType &registerWord)
435  {
436  CRYPTOPP_ASSERT(IsAligned<WordType>(m_output));
437  CRYPTOPP_ASSERT(IsAligned<WordType>(m_input));
438 
439  if (!NativeByteOrderIs(B::ToEnum()))
440  registerWord = ByteReverse(registerWord);
441 
442  if (m_dir == ENCRYPTION)
443  {
444  if (m_input == NULLPTR)
445  {
446  CRYPTOPP_ASSERT(m_output == NULLPTR);
447  }
448  else
449  {
450  WordType ct = *(const WordType *)m_input ^ registerWord;
451  registerWord = ct;
452  *(WordType*)m_output = ct;
453  m_input += sizeof(WordType);
454  m_output += sizeof(WordType);
455  }
456  }
457  else
458  {
459  WordType ct = *(const WordType *)m_input;
460  *(WordType*)m_output = registerWord ^ ct;
461  registerWord = ct;
462  m_input += sizeof(WordType);
463  m_output += sizeof(WordType);
464  }
465 
466  // registerWord is left unreversed so it can be xor-ed with further input
467 
468  return *this;
469  }
470 
471  byte *m_output;
472  const byte *m_input;
473  CipherDir m_dir;
474  };
475 };
476 
477 /// \brief Base class for feedback based stream ciphers with SymmetricCipher interface
478 /// \tparam BASE AbstractPolicyHolder base class
479 template <class BASE>
480 class CRYPTOPP_NO_VTABLE CFB_CipherTemplate : public BASE
481 {
482 public:
483  /// \brief Apply keystream to data
484  /// \param outString a buffer to write the transformed data
485  /// \param inString a buffer to read the data
486  /// \param length the size fo the buffers, in bytes
487  /// \details This is the primary method to operate a stream cipher. For example:
488  /// <pre>
489  /// size_t size = 30;
490  /// byte plain[size] = "Do or do not; there is no try";
491  /// byte cipher[size];
492  /// ...
493  /// ChaCha20 chacha(key, keySize);
494  /// chacha.ProcessData(cipher, plain, size);
495  /// </pre>
496  void ProcessData(byte *outString, const byte *inString, size_t length);
497 
498  /// \brief Resynchronize the cipher
499  /// \param iv a byte array used to resynchronize the cipher
500  /// \param length the size of the IV array
501  void Resynchronize(const byte *iv, int length=-1);
502 
503  /// \brief Provides number of ideal bytes to process
504  /// \returns the ideal number of bytes to process
505  /// \details Internally, the default implementation returns GetBytesPerIteration()
506  /// \sa GetBytesPerIteration() and GetOptimalNextBlockSize()
507  unsigned int OptimalBlockSize() const {return this->GetPolicy().GetBytesPerIteration();}
508 
509  /// \brief Provides number of ideal bytes to process
510  /// \returns the ideal number of bytes to process
511  /// \details Internally, the default implementation returns remaining unprocessed bytes
512  /// \sa GetBytesPerIteration() and OptimalBlockSize()
513  unsigned int GetOptimalNextBlockSize() const {return (unsigned int)m_leftOver;}
514 
515  /// \brief Provides number of ideal data alignment
516  /// \returns the ideal data alignment, in bytes
517  /// \sa GetAlignment() and OptimalBlockSize()
518  unsigned int OptimalDataAlignment() const {return this->GetPolicy().GetAlignment();}
519 
520  /// \brief Flag indicating random access
521  /// \returns true if the cipher is seekable, false otherwise
522  /// \sa Seek()
523  bool IsRandomAccess() const {return false;}
524 
525  /// \brief Determines if the cipher is self inverting
526  /// \returns true if the stream cipher is self inverting, false otherwise
527  bool IsSelfInverting() const {return false;}
528 
529  typedef typename BASE::PolicyInterface PolicyInterface;
530 
531 protected:
532  virtual void CombineMessageAndShiftRegister(byte *output, byte *reg, const byte *message, size_t length) =0;
533 
534  void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params);
535 
536  size_t m_leftOver;
537 };
538 
539 /// \brief Base class for feedback based stream ciphers in the forward direction with SymmetricCipher interface
540 /// \tparam BASE AbstractPolicyHolder base class
541 template <class BASE = AbstractPolicyHolder<CFB_CipherAbstractPolicy, SymmetricCipher> >
542 class CRYPTOPP_NO_VTABLE CFB_EncryptionTemplate : public CFB_CipherTemplate<BASE>
543 {
544  bool IsForwardTransformation() const {return true;}
545  void CombineMessageAndShiftRegister(byte *output, byte *reg, const byte *message, size_t length);
546 };
547 
548 /// \brief Base class for feedback based stream ciphers in the reverse direction with SymmetricCipher interface
549 /// \tparam BASE AbstractPolicyHolder base class
550 template <class BASE = AbstractPolicyHolder<CFB_CipherAbstractPolicy, SymmetricCipher> >
551 class CRYPTOPP_NO_VTABLE CFB_DecryptionTemplate : public CFB_CipherTemplate<BASE>
552 {
553  bool IsForwardTransformation() const {return false;}
554  void CombineMessageAndShiftRegister(byte *output, byte *reg, const byte *message, size_t length);
555 };
556 
557 /// \brief Base class for feedback based stream ciphers with a mandatory block size
558 /// \tparam BASE CFB_EncryptionTemplate or CFB_DecryptionTemplate base class
559 template <class BASE>
560 class CFB_RequireFullDataBlocks : public BASE
561 {
562 public:
563  unsigned int MandatoryBlockSize() const {return this->OptimalBlockSize();}
564 };
565 
566 /// \brief SymmetricCipher implementation
567 /// \tparam BASE AbstractPolicyHolder derived base class
568 /// \tparam INFO AbstractPolicyHolder derived information class
569 /// \sa Weak::ARC4, ChaCha8, ChaCha12, ChaCha20, Salsa20, SEAL, Sosemanuk, WAKE
570 template <class BASE, class INFO = BASE>
571 class SymmetricCipherFinal : public AlgorithmImpl<SimpleKeyingInterfaceImpl<BASE, INFO>, INFO>
572 {
573 public:
574  virtual ~SymmetricCipherFinal() {}
575 
576  /// \brief Construct a stream cipher
578 
579  /// \brief Construct a stream cipher
580  /// \param key a byte array used to key the cipher
581  /// \details This overload uses DEFAULT_KEYLENGTH
582  SymmetricCipherFinal(const byte *key)
583  {this->SetKey(key, this->DEFAULT_KEYLENGTH);}
584 
585  /// \brief Construct a stream cipher
586  /// \param key a byte array used to key the cipher
587  /// \param length the size of the key array
588  SymmetricCipherFinal(const byte *key, size_t length)
589  {this->SetKey(key, length);}
590 
591  /// \brief Construct a stream cipher
592  /// \param key a byte array used to key the cipher
593  /// \param length the size of the key array
594  /// \param iv a byte array used as an initialization vector
595  SymmetricCipherFinal(const byte *key, size_t length, const byte *iv)
596  {this->SetKeyWithIV(key, length, iv);}
597 
598  /// \brief Clone a SymmetricCipher
599  /// \returns a new SymmetricCipher based on this object
600  Clonable * Clone() const {return static_cast<SymmetricCipher *>(new SymmetricCipherFinal<BASE, INFO>(*this));}
601 };
602 
603 NAMESPACE_END
604 
605 #ifdef CRYPTOPP_MANUALLY_INSTANTIATE_TEMPLATES
606 #include "strciphr.cpp"
607 #endif
608 
609 NAMESPACE_BEGIN(CryptoPP)
615 
616 NAMESPACE_END
617 
618 #if CRYPTOPP_MSC_VERSION
619 # pragma warning(pop)
620 #endif
621 
622 #endif
Base class for all exceptions thrown by the library.
Definition: cryptlib.h:156
unsigned int GetOptimalNextBlockSize() const
Provides number of ideal bytes to process.
Definition: strciphr.h:513
Standard names for retrieving values by name when working with NameValuePairs.
bool CanOperateKeystream() const
Flag indicating.
Definition: strciphr.h:206
bool NativeByteOrderIs(ByteOrder order)
Determines whether order follows native byte ordering.
Definition: misc.h:1066
Output buffer is aligned.
Definition: strciphr.h:78
SymmetricCipherFinal(const byte *key)
Construct a stream cipher.
Definition: strciphr.h:582
unsigned int OptimalBlockSize() const
Provides number of ideal bytes to process.
Definition: strciphr.h:297
Input buffer is aligned.
Definition: strciphr.h:80
bool IsRandomAccess() const
Flag indicating random access.
Definition: strciphr.h:523
Base class for feedback based stream ciphers.
Definition: strciphr.h:398
Base class for additive stream ciphers.
Definition: strciphr.h:181
virtual void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount)
Operates the keystream.
Definition: strciphr.h:148
unsigned int GetOptimalNextBlockSize() const
Provides number of ideal bytes to process.
Definition: strciphr.h:303
XOR the input buffer and keystream, write to the aligned output buffer.
Definition: strciphr.h:98
unsigned int GetBytesPerIteration() const
Provides number of bytes operated upon during an iteration.
Definition: strciphr.h:411
XOR the input buffer and keystream, write to the output buffer.
Definition: strciphr.h:94
CipherDir
Specifies a direction for a cipher to operate.
Definition: cryptlib.h:121
Abstract base classes that provide a uniform interface to this library.
Base class for feedback based stream ciphers with SymmetricCipher interface.
Definition: strciphr.h:480
unsigned int OptimalDataAlignment() const
Provides number of ideal data alignment.
Definition: strciphr.h:308
Some other error occurred not belonging to other categories.
Definition: cryptlib.h:175
Library configuration file.
virtual unsigned int GetOptimalBlockSize() const
Provides number of ideal bytes to process.
Definition: strciphr.h:122
Interface for random number generators.
Definition: cryptlib.h:1327
unsigned int GetAlignment() const
Provides data alignment requirements.
Definition: strciphr.h:191
Wirte the keystream to the output buffer, input is NULL.
Definition: strciphr.h:90
SecBlock<byte> typedef.
Definition: secblock.h:822
Stream cipher policy object.
Definition: strciphr.h:64
virtual bool CanOperateKeystream() const
Flag indicating.
Definition: strciphr.h:138
Interface for cloning objects.
Definition: cryptlib.h:561
virtual void WriteKeystream(byte *keystream, size_t iterationCount)
Generate the keystream.
Definition: strciphr.h:132
Policy object for additive stream ciphers.
Definition: strciphr.h:103
the cipher is performing encryption
Definition: cryptlib.h:123
Classes and functions for secure memory allocations.
void TransformRegister()
Perform one iteration in the forward direction.
Definition: strciphr.h:418
bool IsAlignedOn(const void *ptr, unsigned int alignment)
Determines whether ptr is aligned to a minimum value.
Definition: misc.h:1025
Input buffer is NULL.
Definition: strciphr.h:82
Base class for feedback based stream ciphers in the reverse direction with SymmetricCipher interface...
Definition: strciphr.h:551
bool IsSelfInverting() const
Determines if the cipher is self inverting.
Definition: strciphr.h:312
Provides alternate access to a feedback register.
Definition: strciphr.h:426
unsigned int GetBytesPerIteration() const
Provides number of bytes operated upon during an iteration.
Definition: strciphr.h:197
A method was called which was not implemented.
Definition: cryptlib.h:221
virtual unsigned int GetAlignment() const
Provides data alignment requirements.
Definition: strciphr.h:111
bool CanIterate() const
Flag indicating iteration support.
Definition: strciphr.h:415
RegisterOutput & operator()(WordType &registerWord)
XOR feedback register with data.
Definition: strciphr.h:434
virtual unsigned int GetBytesPerIteration() const =0
Provides number of bytes operated upon during an iteration.
Classes and functions for implementing secret key algorithms.
virtual void SeekToIteration(lword iterationCount)
Seeks to a random position in the stream.
Definition: strciphr.h:171
unsigned int OptimalBlockSize() const
Provides number of ideal bytes to process.
Definition: strciphr.h:507
Interface for one direction (encryption or decryption) of a stream cipher or cipher mode...
Definition: cryptlib.h:1236
Base class for feedback based stream ciphers with a mandatory block size.
Definition: strciphr.h:560
Policy object for feeback based stream ciphers.
Definition: strciphr.h:343
Base class for feedback based stream ciphers in the forward direction with SymmetricCipher interface...
Definition: strciphr.h:542
SymmetricCipherFinal()
Construct a stream cipher.
Definition: strciphr.h:577
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:60
bool IsSelfInverting() const
Determines if the cipher is self inverting.
Definition: strciphr.h:527
bool IsRandomAccess() const
Flag indicating random access.
Definition: strciphr.h:321
virtual unsigned int GetIterationsToBuffer() const =0
Provides buffer size based on iterations.
unsigned int OptimalDataAlignment() const
Provides number of ideal data alignment.
Definition: strciphr.h:518
XOR the aligned input buffer and keystream, write to the aligned output buffer.
Definition: strciphr.h:100
virtual bool CanIterate() const
Flag indicating iteration support.
Definition: strciphr.h:368
SymmetricCipherFinal(const byte *key, size_t length, const byte *iv)
Construct a stream cipher.
Definition: strciphr.h:595
Clonable * Clone() const
Clone a SymmetricCipher.
Definition: strciphr.h:600
virtual void CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length)
Resynchronize the cipher.
Definition: strciphr.h:161
virtual void Iterate(byte *output, const byte *input, CipherDir dir, size_t iterationCount)
Iterate the cipher.
Definition: strciphr.h:376
unsigned int GetAlignment() const
Provides data alignment requirements.
Definition: strciphr.h:406
KeystreamOperation
Keystream operation flags.
Definition: strciphr.h:88
SymmetricCipherFinal(const byte *key, size_t length)
Construct a stream cipher.
Definition: strciphr.h:588
virtual void CipherResynchronize(const byte *iv, size_t length)
Resynchronize the cipher.
Definition: strciphr.h:389
Crypto++ library namespace.
bool IsForwardTransformation() const
Determines if the cipher is a forward transformation.
Definition: strciphr.h:316
SymmetricCipher implementation.
Definition: strciphr.h:571
Wirte the keystream to the aligned output buffer, input is NULL.
Definition: strciphr.h:92
unsigned int GetIterationsToBuffer() const
Provides buffer size based on iterations.
Definition: strciphr.h:201
byte ByteReverse(byte value)
Reverses bytes in a 8-bit value.
Definition: misc.h:1833
Base class for additive stream ciphers with SymmetricCipher interface.
Definition: strciphr.h:261
Access a stream cipher policy object.
Definition: strciphr.h:49
XOR the aligned input buffer and keystream, write to the output buffer.
Definition: strciphr.h:96
KeystreamOperationFlags
Keystream operation flags.
Definition: strciphr.h:76
Interface for retrieving values given their names.
Definition: cryptlib.h:291
Base class information.
Definition: simple.h:36