Crypto++ 8.6
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
9/// methods to query which features are supported by a cipher.
10/// \details Here's an explanation of these classes. The word "policy" is used here to
11/// mean a class with a set of methods that must be implemented by individual stream
12/// cipher implementations. This is usually much simpler than the full stream cipher
13/// API, which is implemented by either AdditiveCipherTemplate or CFB_CipherTemplate
14/// using the policy. So for example, an implementation of SEAL only needs to implement
15/// the AdditiveCipherAbstractPolicy interface (since it's an additive cipher, i.e., it
16/// xors a keystream into the plaintext). 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
21/// need to take a policy class as a template parameter (although this is allowed), so
22/// that their code is not duplicated for each new cipher. Instead they each get a
23/// 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 ConcretePolicyHolder class. Finally, SymmetricCipherFinal implements the
26/// constructors and 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
43NAMESPACE_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
48template <class POLICY_INTERFACE, class BASE = Empty>
49class CRYPTOPP_NO_VTABLE AbstractPolicyHolder : public BASE
50{
51public:
52 typedef POLICY_INTERFACE PolicyInterface;
53 virtual ~AbstractPolicyHolder() {}
54
55protected:
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
63template <class POLICY, class BASE, class POLICY_INTERFACE = typename BASE::PolicyInterface>
64class ConcretePolicyHolder : public BASE, protected POLICY
65{
66public:
67 virtual ~ConcretePolicyHolder() {}
68protected:
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
82 INPUT_NULL = 4
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
102
103/// \brief Policy object for additive stream ciphers
104struct CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AdditiveCipherAbstractPolicy
105{
107
108 /// \brief Provides data alignment requirements
109 /// \return data alignment requirements, in bytes
110 /// \details Internally, the default implementation returns 1. If the stream cipher is implemented
111 /// using an SSE2 ASM or intrinsics, then the value returned is usually 16.
112 virtual unsigned int GetAlignment() const {return 1;}
113
114 /// \brief Provides number of bytes operated upon during an iteration
115 /// \return bytes operated upon during an iteration, in bytes
116 /// \sa GetOptimalBlockSize()
117 virtual unsigned int GetBytesPerIteration() const =0;
118
119 /// \brief Provides number of ideal bytes to process
120 /// \return the ideal number of bytes to process
121 /// \details Internally, the default implementation returns GetBytesPerIteration()
122 /// \sa GetBytesPerIteration()
123 virtual unsigned int GetOptimalBlockSize() const {return GetBytesPerIteration();}
124
125 /// \brief Provides buffer size based on iterations
126 /// \return the buffer size based on iterations, in bytes
127 virtual unsigned int GetIterationsToBuffer() const =0;
128
129 /// \brief Generate the keystream
130 /// \param keystream the key stream
131 /// \param iterationCount the number of iterations to generate the key stream
132 /// \sa CanOperateKeystream(), OperateKeystream(), WriteKeystream()
133 virtual void WriteKeystream(byte *keystream, size_t iterationCount)
134 {OperateKeystream(KeystreamOperation(INPUT_NULL | static_cast<KeystreamOperationFlags>(IsAlignedOn(keystream, GetAlignment()))), keystream, NULLPTR, iterationCount);}
135
136 /// \brief Flag indicating
137 /// \return true if the stream can be generated independent of the transformation input, false otherwise
138 /// \sa CanOperateKeystream(), OperateKeystream(), WriteKeystream()
139 virtual bool CanOperateKeystream() const {return false;}
140
141 /// \brief Operates the keystream
142 /// \param operation the operation with additional flags
143 /// \param output the output buffer
144 /// \param input the input buffer
145 /// \param iterationCount the number of iterations to perform on the input
146 /// \details OperateKeystream() will attempt to operate upon GetOptimalBlockSize() buffer,
147 /// which will be derived from GetBytesPerIteration().
148 /// \sa CanOperateKeystream(), OperateKeystream(), WriteKeystream(), KeystreamOperation()
149 virtual void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount)
150 {CRYPTOPP_UNUSED(operation); CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(input);
151 CRYPTOPP_UNUSED(iterationCount); CRYPTOPP_ASSERT(false);}
152
153 /// \brief Key the cipher
154 /// \param params set of NameValuePairs use to initialize this object
155 /// \param key a byte array used to key the cipher
156 /// \param length the size of the key array
157 virtual void CipherSetKey(const NameValuePairs &params, const byte *key, size_t length) =0;
158
159 /// \brief Resynchronize the cipher
160 /// \param keystreamBuffer the keystream buffer
161 /// \param iv a byte array used to resynchronize the cipher
162 /// \param length the size of the IV array
163 virtual void CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length)
164 {CRYPTOPP_UNUSED(keystreamBuffer); CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(length);
165 throw NotImplemented("SimpleKeyingInterface: this object doesn't support resynchronization");}
166
167 /// \brief Flag indicating random access
168 /// \return true if the cipher is seekable, false otherwise
169 /// \sa SeekToIteration()
170 virtual bool CipherIsRandomAccess() const =0;
171
172 /// \brief Seeks to a random position in the stream
173 /// \sa CipherIsRandomAccess()
174 virtual void SeekToIteration(lword iterationCount)
175 {CRYPTOPP_UNUSED(iterationCount); CRYPTOPP_ASSERT(!CipherIsRandomAccess());
176 throw NotImplemented("StreamTransformation: this object doesn't support random access");}
177
178 /// \brief Retrieve the provider of this algorithm
179 /// \return the algorithm provider
180 /// \details The algorithm provider can be a name like "C++", "SSE", "NEON", "AESNI",
181 /// "ARMv8" and "Power8". C++ is standard C++ code. Other labels, like SSE,
182 /// usually indicate a specialized implementation using instructions from a higher
183 /// instruction set architecture (ISA). Future labels may include external hardware
184 /// like a hardware security module (HSM).
185 /// \details Generally speaking Wei Dai's original IA-32 ASM code falls under "SSE2".
186 /// Labels like "SSSE3" and "SSE4.1" follow after Wei's code and use intrinsics
187 /// instead of ASM.
188 /// \details Algorithms which combine different instructions or ISAs provide the
189 /// dominant one. For example on x86 <tt>AES/GCM</tt> returns "AESNI" rather than
190 /// "CLMUL" or "AES+SSE4.1" or "AES+CLMUL" or "AES+SSE4.1+CLMUL".
191 /// \note Provider is not universally implemented yet.
192 virtual std::string AlgorithmProvider() const { return "C++"; }
193};
194
195/// \brief Base class for additive stream ciphers
196/// \tparam WT word type
197/// \tparam W count of words
198/// \tparam X bytes per iteration count
199/// \tparam BASE AdditiveCipherAbstractPolicy derived base class
200template <typename WT, unsigned int W, unsigned int X = 1, class BASE = AdditiveCipherAbstractPolicy>
201struct CRYPTOPP_NO_VTABLE AdditiveCipherConcretePolicy : public BASE
202{
203 /// \brief Word type for the cipher
204 typedef WT WordType;
205
206 /// \brief Number of bytes for an iteration
207 /// \details BYTES_PER_ITERATION is the product <tt>sizeof(WordType) * W</tt>.
208 /// For example, ChaCha uses 16 each <tt>word32</tt>, and the value of
209 /// BYTES_PER_ITERATION is 64. Each invocation of the ChaCha block function
210 /// produces 64 bytes of keystream.
211 CRYPTOPP_CONSTANT(BYTES_PER_ITERATION = sizeof(WordType) * W);
212
214
215 /// \brief Provides data alignment requirements
216 /// \return data alignment requirements, in bytes
217 /// \details Internally, the default implementation returns 1. If the stream
218 /// cipher is implemented using an SSE2 ASM or intrinsics, then the value
219 /// returned is usually 16.
220 unsigned int GetAlignment() const {return GetAlignmentOf<WordType>();}
221
222 /// \brief Provides number of bytes operated upon during an iteration
223 /// \return bytes operated upon during an iteration, in bytes
224 /// \sa GetOptimalBlockSize()
225 unsigned int GetBytesPerIteration() const {return BYTES_PER_ITERATION;}
226
227 /// \brief Provides buffer size based on iterations
228 /// \return the buffer size based on iterations, in bytes
229 unsigned int GetIterationsToBuffer() const {return X;}
230
231 /// \brief Flag indicating
232 /// \return true if the stream can be generated independent of the
233 /// transformation input, false otherwise
234 /// \sa CanOperateKeystream(), OperateKeystream(), WriteKeystream()
235 bool CanOperateKeystream() const {return true;}
236
237 /// \brief Operates the keystream
238 /// \param operation the operation with additional flags
239 /// \param output the output buffer
240 /// \param input the input buffer
241 /// \param iterationCount the number of iterations to perform on the input
242 /// \details OperateKeystream() will attempt to operate upon GetOptimalBlockSize() buffer,
243 /// which will be derived from GetBytesPerIteration().
244 /// \sa CanOperateKeystream(), OperateKeystream(), WriteKeystream(), KeystreamOperation()
245 virtual void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount) =0;
246};
247
248/// \brief Helper macro to implement OperateKeystream
249/// \param x KeystreamOperation mask
250/// \param b Endian order
251/// \param i index in output buffer
252/// \param a value to output
253#define CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, b, i, a) \
254 PutWord(((x & OUTPUT_ALIGNED) != 0), b, output+i*sizeof(WordType), (x & INPUT_NULL) ? (a) : (a) ^ GetWord<WordType>(((x & INPUT_ALIGNED) != 0), b, input+i*sizeof(WordType)));
255
256/// \brief Helper macro to implement OperateKeystream
257/// \param x KeystreamOperation mask
258/// \param i index in output buffer
259/// \param a value to output
260#define CRYPTOPP_KEYSTREAM_OUTPUT_XMM(x, i, a) {\
261 __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));\
262 if (x & OUTPUT_ALIGNED) _mm_store_si128((__m128i *)output+i, t);\
263 else _mm_storeu_si128((__m128i *)output+i, t);}
264
265/// \brief Helper macro to implement OperateKeystream
266#define CRYPTOPP_KEYSTREAM_OUTPUT_SWITCH(x, y) \
267 switch (operation) \
268 { \
269 case WRITE_KEYSTREAM: \
270 x(EnumToInt(WRITE_KEYSTREAM)) \
271 break; \
272 case XOR_KEYSTREAM: \
273 x(EnumToInt(XOR_KEYSTREAM)) \
274 input += y; \
275 break; \
276 case XOR_KEYSTREAM_INPUT_ALIGNED: \
277 x(EnumToInt(XOR_KEYSTREAM_INPUT_ALIGNED)) \
278 input += y; \
279 break; \
280 case XOR_KEYSTREAM_OUTPUT_ALIGNED: \
281 x(EnumToInt(XOR_KEYSTREAM_OUTPUT_ALIGNED)) \
282 input += y; \
283 break; \
284 case WRITE_KEYSTREAM_ALIGNED: \
285 x(EnumToInt(WRITE_KEYSTREAM_ALIGNED)) \
286 break; \
287 case XOR_KEYSTREAM_BOTH_ALIGNED: \
288 x(EnumToInt(XOR_KEYSTREAM_BOTH_ALIGNED)) \
289 input += y; \
290 break; \
291 } \
292 output += y;
293
294/// \brief Base class for additive stream ciphers with SymmetricCipher interface
295/// \tparam BASE AbstractPolicyHolder base class
296template <class BASE = AbstractPolicyHolder<AdditiveCipherAbstractPolicy, SymmetricCipher> >
297class CRYPTOPP_NO_VTABLE AdditiveCipherTemplate : public BASE, public RandomNumberGenerator
298{
299public:
300 virtual ~AdditiveCipherTemplate() {}
301 AdditiveCipherTemplate() : m_leftOver(0) {}
302
303 /// \brief Generate random array of bytes
304 /// \param output the byte buffer
305 /// \param size the length of the buffer, in bytes
306 /// \details All generated values are uniformly distributed over the range specified
307 /// within the constraints of a particular generator.
308 void GenerateBlock(byte *output, size_t size);
309
310 /// \brief Apply keystream to data
311 /// \param outString a buffer to write the transformed data
312 /// \param inString a buffer to read the data
313 /// \param length the size of the buffers, in bytes
314 /// \details This is the primary method to operate a stream cipher. For example:
315 /// <pre>
316 /// size_t size = 30;
317 /// byte plain[size] = "Do or do not; there is no try";
318 /// byte cipher[size];
319 /// ...
320 /// ChaCha20 chacha(key, keySize);
321 /// chacha.ProcessData(cipher, plain, size);
322 /// </pre>
323 void ProcessData(byte *outString, const byte *inString, size_t length);
324
325 /// \brief Resynchronize the cipher
326 /// \param iv a byte array used to resynchronize the cipher
327 /// \param length the size of the IV array
328 void Resynchronize(const byte *iv, int length=-1);
329
330 /// \brief Provides number of ideal bytes to process
331 /// \return the ideal number of bytes to process
332 /// \details Internally, the default implementation returns GetBytesPerIteration()
333 /// \sa GetBytesPerIteration() and GetOptimalNextBlockSize()
334 unsigned int OptimalBlockSize() const {return this->GetPolicy().GetOptimalBlockSize();}
335
336 /// \brief Provides number of ideal bytes to process
337 /// \return the ideal number of bytes to process
338 /// \details Internally, the default implementation returns remaining unprocessed bytes
339 /// \sa GetBytesPerIteration() and OptimalBlockSize()
340 unsigned int GetOptimalNextBlockSize() const {return (unsigned int)this->m_leftOver;}
341
342 /// \brief Provides number of ideal data alignment
343 /// \return the ideal data alignment, in bytes
344 /// \sa GetAlignment() and OptimalBlockSize()
345 unsigned int OptimalDataAlignment() const {return this->GetPolicy().GetAlignment();}
346
347 /// \brief Determines if the cipher is self inverting
348 /// \return true if the stream cipher is self inverting, false otherwise
349 bool IsSelfInverting() const {return true;}
350
351 /// \brief Determines if the cipher is a forward transformation
352 /// \return true if the stream cipher is a forward transformation, false otherwise
353 bool IsForwardTransformation() const {return true;}
354
355 /// \brief Flag indicating random access
356 /// \return true if the cipher is seekable, false otherwise
357 /// \sa Seek()
358 bool IsRandomAccess() const {return this->GetPolicy().CipherIsRandomAccess();}
359
360 /// \brief Seeks to a random position in the stream
361 /// \param position the absolute position in the stream
362 /// \sa IsRandomAccess()
363 void Seek(lword position);
364
365 /// \brief Retrieve the provider of this algorithm
366 /// \return the algorithm provider
367 /// \details The algorithm provider can be a name like "C++", "SSE", "NEON", "AESNI",
368 /// "ARMv8" and "Power8". C++ is standard C++ code. Other labels, like SSE,
369 /// usually indicate a specialized implementation using instructions from a higher
370 /// instruction set architecture (ISA). Future labels may include external hardware
371 /// like a hardware security module (HSM).
372 /// \details Generally speaking Wei Dai's original IA-32 ASM code falls under "SSE2".
373 /// Labels like "SSSE3" and "SSE4.1" follow after Wei's code and use intrinsics
374 /// instead of ASM.
375 /// \details Algorithms which combine different instructions or ISAs provide the
376 /// dominant one. For example on x86 <tt>AES/GCM</tt> returns "AESNI" rather than
377 /// "CLMUL" or "AES+SSE4.1" or "AES+CLMUL" or "AES+SSE4.1+CLMUL".
378 /// \note Provider is not universally implemented yet.
379 std::string AlgorithmProvider() const { return this->GetPolicy().AlgorithmProvider(); }
380
381 typedef typename BASE::PolicyInterface PolicyInterface;
382
383protected:
384 void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params);
385
386 unsigned int GetBufferByteSize(const PolicyInterface &policy) const {return policy.GetBytesPerIteration() * policy.GetIterationsToBuffer();}
387
388 inline byte * KeystreamBufferBegin() {return this->m_buffer.data();}
389 inline byte * KeystreamBufferEnd() {return (PtrAdd(this->m_buffer.data(), this->m_buffer.size()));}
390
391 // m_tempOutString added due to GH #1010
392 AlignedSecByteBlock m_buffer, m_tempOutString;
393 size_t m_leftOver;
394};
395
396/// \brief Policy object for feeback based stream ciphers
397class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CFB_CipherAbstractPolicy
398{
399public:
400 virtual ~CFB_CipherAbstractPolicy() {}
401
402 /// \brief Provides data alignment requirements
403 /// \return 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 virtual unsigned int GetAlignment() const =0;
407
408 /// \brief Provides number of bytes operated upon during an iteration
409 /// \return bytes operated upon during an iteration, in bytes
410 /// \sa GetOptimalBlockSize()
411 virtual unsigned int GetBytesPerIteration() const =0;
412
413 /// \brief Access the feedback register
414 /// \return pointer to the first byte of the feedback register
415 virtual byte * GetRegisterBegin() =0;
416
417 /// \brief TODO
418 virtual void TransformRegister() =0;
419
420 /// \brief Flag indicating iteration support
421 /// \return true if the cipher supports iteration, false otherwise
422 virtual bool CanIterate() const {return false;}
423
424 /// \brief Iterate the cipher
425 /// \param output the output buffer
426 /// \param input the input buffer
427 /// \param dir the direction of the cipher
428 /// \param iterationCount the number of iterations to perform on the input
429 /// \sa IsSelfInverting() and IsForwardTransformation()
430 virtual void Iterate(byte *output, const byte *input, CipherDir dir, size_t iterationCount)
431 {CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(dir);
432 CRYPTOPP_UNUSED(iterationCount); CRYPTOPP_ASSERT(false);
433 throw Exception(Exception::OTHER_ERROR, "SimpleKeyingInterface: unexpected error");}
434
435 /// \brief Key the cipher
436 /// \param params set of NameValuePairs use to initialize this object
437 /// \param key a byte array used to key the cipher
438 /// \param length the size of the key array
439 virtual void CipherSetKey(const NameValuePairs &params, const byte *key, size_t length) =0;
440
441 /// \brief Resynchronize the cipher
442 /// \param iv a byte array used to resynchronize the cipher
443 /// \param length the size of the IV array
444 virtual void CipherResynchronize(const byte *iv, size_t length)
445 {CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(length);
446 throw NotImplemented("SimpleKeyingInterface: this object doesn't support resynchronization");}
447
448 /// \brief Retrieve the provider of this algorithm
449 /// \return the algorithm provider
450 /// \details The algorithm provider can be a name like "C++", "SSE", "NEON", "AESNI",
451 /// "ARMv8" and "Power8". C++ is standard C++ code. Other labels, like SSE,
452 /// usually indicate a specialized implementation using instructions from a higher
453 /// instruction set architecture (ISA). Future labels may include external hardware
454 /// like a hardware security module (HSM).
455 /// \details Generally speaking Wei Dai's original IA-32 ASM code falls under "SSE2".
456 /// Labels like "SSSE3" and "SSE4.1" follow after Wei's code and use intrinsics
457 /// instead of ASM.
458 /// \details Algorithms which combine different instructions or ISAs provide the
459 /// dominant one. For example on x86 <tt>AES/GCM</tt> returns "AESNI" rather than
460 /// "CLMUL" or "AES+SSE4.1" or "AES+CLMUL" or "AES+SSE4.1+CLMUL".
461 /// \note Provider is not universally implemented yet.
462 virtual std::string AlgorithmProvider() const { return "C++"; }
463};
464
465/// \brief Base class for feedback based stream ciphers
466/// \tparam WT word type
467/// \tparam W count of words
468/// \tparam BASE CFB_CipherAbstractPolicy derived base class
469template <typename WT, unsigned int W, class BASE = CFB_CipherAbstractPolicy>
470struct CRYPTOPP_NO_VTABLE CFB_CipherConcretePolicy : public BASE
471{
472 typedef WT WordType;
473
474 virtual ~CFB_CipherConcretePolicy() {}
475
476 /// \brief Provides data alignment requirements
477 /// \return data alignment requirements, in bytes
478 /// \details Internally, the default implementation returns 1. If the stream cipher is implemented
479 /// using an SSE2 ASM or intrinsics, then the value returned is usually 16.
480 unsigned int GetAlignment() const {return sizeof(WordType);}
481
482 /// \brief Provides number of bytes operated upon during an iteration
483 /// \return bytes operated upon during an iteration, in bytes
484 /// \sa GetOptimalBlockSize()
485 unsigned int GetBytesPerIteration() const {return sizeof(WordType) * W;}
486
487 /// \brief Flag indicating iteration support
488 /// \return true if the cipher supports iteration, false otherwise
489 bool CanIterate() const {return true;}
490
491 /// \brief Perform one iteration in the forward direction
492 void TransformRegister() {this->Iterate(NULLPTR, NULLPTR, ENCRYPTION, 1);}
493
494 /// \brief Provides alternate access to a feedback register
495 /// \tparam B enumeration indicating endianness
496 /// \details RegisterOutput() provides alternate access to the feedback register. The
497 /// enumeration B is BigEndian or LittleEndian. Repeatedly applying operator()
498 /// results in advancing in the register.
499 template <class B>
501 {
502 RegisterOutput(byte *output, const byte *input, CipherDir dir)
503 : m_output(output), m_input(input), m_dir(dir) {}
504
505 /// \brief XOR feedback register with data
506 /// \param registerWord data represented as a word type
507 /// \return reference to the next feedback register word
508 inline RegisterOutput& operator()(WordType &registerWord)
509 {
510 //CRYPTOPP_ASSERT(IsAligned<WordType>(m_output));
511 //CRYPTOPP_ASSERT(IsAligned<WordType>(m_input));
512
513 if (!NativeByteOrderIs(B::ToEnum()))
514 registerWord = ByteReverse(registerWord);
515
516 if (m_dir == ENCRYPTION)
517 {
518 if (m_input == NULLPTR)
519 {
520 CRYPTOPP_ASSERT(m_output == NULLPTR);
521 }
522 else
523 {
524 // WordType ct = *(const WordType *)m_input ^ registerWord;
525 WordType ct = GetWord<WordType>(false, NativeByteOrder::ToEnum(), m_input) ^ registerWord;
526 registerWord = ct;
527
528 // *(WordType*)m_output = ct;
529 PutWord<WordType>(false, NativeByteOrder::ToEnum(), m_output, ct);
530
531 m_input += sizeof(WordType);
532 m_output += sizeof(WordType);
533 }
534 }
535 else
536 {
537 // WordType ct = *(const WordType *)m_input;
538 WordType ct = GetWord<WordType>(false, NativeByteOrder::ToEnum(), m_input);
539
540 // *(WordType*)m_output = registerWord ^ ct;
541 PutWord<WordType>(false, NativeByteOrder::ToEnum(), m_output, registerWord ^ ct);
542 registerWord = ct;
543
544 m_input += sizeof(WordType);
545 m_output += sizeof(WordType);
546 }
547
548 // registerWord is left unreversed so it can be xor-ed with further input
549
550 return *this;
551 }
552
553 byte *m_output;
554 const byte *m_input;
555 CipherDir m_dir;
556 };
557};
558
559/// \brief Base class for feedback based stream ciphers with SymmetricCipher interface
560/// \tparam BASE AbstractPolicyHolder base class
561template <class BASE>
562class CRYPTOPP_NO_VTABLE CFB_CipherTemplate : public BASE
563{
564public:
565 virtual ~CFB_CipherTemplate() {}
566 CFB_CipherTemplate() : m_leftOver(0) {}
567
568 /// \brief Apply keystream to data
569 /// \param outString a buffer to write the transformed data
570 /// \param inString a buffer to read the data
571 /// \param length the size of the buffers, in bytes
572 /// \details This is the primary method to operate a stream cipher. For example:
573 /// <pre>
574 /// size_t size = 30;
575 /// byte plain[size] = "Do or do not; there is no try";
576 /// byte cipher[size];
577 /// ...
578 /// ChaCha20 chacha(key, keySize);
579 /// chacha.ProcessData(cipher, plain, size);
580 /// </pre>
581 void ProcessData(byte *outString, const byte *inString, size_t length);
582
583 /// \brief Resynchronize the cipher
584 /// \param iv a byte array used to resynchronize the cipher
585 /// \param length the size of the IV array
586 void Resynchronize(const byte *iv, int length=-1);
587
588 /// \brief Provides number of ideal bytes to process
589 /// \return the ideal number of bytes to process
590 /// \details Internally, the default implementation returns GetBytesPerIteration()
591 /// \sa GetBytesPerIteration() and GetOptimalNextBlockSize()
592 unsigned int OptimalBlockSize() const {return this->GetPolicy().GetBytesPerIteration();}
593
594 /// \brief Provides number of ideal bytes to process
595 /// \return the ideal number of bytes to process
596 /// \details Internally, the default implementation returns remaining unprocessed bytes
597 /// \sa GetBytesPerIteration() and OptimalBlockSize()
598 unsigned int GetOptimalNextBlockSize() const {return (unsigned int)m_leftOver;}
599
600 /// \brief Provides number of ideal data alignment
601 /// \return the ideal data alignment, in bytes
602 /// \sa GetAlignment() and OptimalBlockSize()
603 unsigned int OptimalDataAlignment() const {return this->GetPolicy().GetAlignment();}
604
605 /// \brief Flag indicating random access
606 /// \return true if the cipher is seekable, false otherwise
607 /// \sa Seek()
608 bool IsRandomAccess() const {return false;}
609
610 /// \brief Determines if the cipher is self inverting
611 /// \return true if the stream cipher is self inverting, false otherwise
612 bool IsSelfInverting() const {return false;}
613
614 /// \brief Retrieve the provider of this algorithm
615 /// \return the algorithm provider
616 /// \details The algorithm provider can be a name like "C++", "SSE", "NEON", "AESNI",
617 /// "ARMv8" and "Power8". C++ is standard C++ code. Other labels, like SSE,
618 /// usually indicate a specialized implementation using instructions from a higher
619 /// instruction set architecture (ISA). Future labels may include external hardware
620 /// like a hardware security module (HSM).
621 /// \details Generally speaking Wei Dai's original IA-32 ASM code falls under "SSE2".
622 /// Labels like "SSSE3" and "SSE4.1" follow after Wei's code and use intrinsics
623 /// instead of ASM.
624 /// \details Algorithms which combine different instructions or ISAs provide the
625 /// dominant one. For example on x86 <tt>AES/GCM</tt> returns "AESNI" rather than
626 /// "CLMUL" or "AES+SSE4.1" or "AES+CLMUL" or "AES+SSE4.1+CLMUL".
627 /// \note Provider is not universally implemented yet.
628 std::string AlgorithmProvider() const { return this->GetPolicy().AlgorithmProvider(); }
629
630 typedef typename BASE::PolicyInterface PolicyInterface;
631
632protected:
633 virtual void CombineMessageAndShiftRegister(byte *output, byte *reg, const byte *message, size_t length) =0;
634
635 void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params);
636
637 // m_tempOutString added due to GH #1010
638 AlignedSecByteBlock m_tempOutString;
639 size_t m_leftOver;
640};
641
642/// \brief Base class for feedback based stream ciphers in the forward direction with SymmetricCipher interface
643/// \tparam BASE AbstractPolicyHolder base class
644template <class BASE = AbstractPolicyHolder<CFB_CipherAbstractPolicy, SymmetricCipher> >
645class CRYPTOPP_NO_VTABLE CFB_EncryptionTemplate : public CFB_CipherTemplate<BASE>
646{
647 bool IsForwardTransformation() const {return true;}
648 void CombineMessageAndShiftRegister(byte *output, byte *reg, const byte *message, size_t length);
649};
650
651/// \brief Base class for feedback based stream ciphers in the reverse direction with SymmetricCipher interface
652/// \tparam BASE AbstractPolicyHolder base class
653template <class BASE = AbstractPolicyHolder<CFB_CipherAbstractPolicy, SymmetricCipher> >
654class CRYPTOPP_NO_VTABLE CFB_DecryptionTemplate : public CFB_CipherTemplate<BASE>
655{
656 bool IsForwardTransformation() const {return false;}
657 void CombineMessageAndShiftRegister(byte *output, byte *reg, const byte *message, size_t length);
658};
659
660/// \brief Base class for feedback based stream ciphers with a mandatory block size
661/// \tparam BASE CFB_EncryptionTemplate or CFB_DecryptionTemplate base class
662template <class BASE>
663class CFB_RequireFullDataBlocks : public BASE
664{
665public:
666 unsigned int MandatoryBlockSize() const {return this->OptimalBlockSize();}
667};
668
669/// \brief SymmetricCipher implementation
670/// \tparam BASE AbstractPolicyHolder derived base class
671/// \tparam INFO AbstractPolicyHolder derived information class
672/// \sa Weak::ARC4, ChaCha8, ChaCha12, ChaCha20, Salsa20, SEAL, Sosemanuk, WAKE
673template <class BASE, class INFO = BASE>
674class SymmetricCipherFinal : public AlgorithmImpl<SimpleKeyingInterfaceImpl<BASE, INFO>, INFO>
675{
676public:
677 virtual ~SymmetricCipherFinal() {}
678
679 /// \brief Construct a stream cipher
681
682 /// \brief Construct a stream cipher
683 /// \param key a byte array used to key the cipher
684 /// \details This overload uses DEFAULT_KEYLENGTH
685 SymmetricCipherFinal(const byte *key)
686 {this->SetKey(key, this->DEFAULT_KEYLENGTH);}
687
688 /// \brief Construct a stream cipher
689 /// \param key a byte array used to key the cipher
690 /// \param length the size of the key array
691 SymmetricCipherFinal(const byte *key, size_t length)
692 {this->SetKey(key, length);}
693
694 /// \brief Construct a stream cipher
695 /// \param key a byte array used to key the cipher
696 /// \param length the size of the key array
697 /// \param iv a byte array used as an initialization vector
698 SymmetricCipherFinal(const byte *key, size_t length, const byte *iv)
699 {this->SetKeyWithIV(key, length, iv);}
700
701 /// \brief Clone a SymmetricCipher
702 /// \return a new SymmetricCipher based on this object
703 Clonable * Clone() const {return static_cast<SymmetricCipher *>(new SymmetricCipherFinal<BASE, INFO>(*this));}
704};
705
706NAMESPACE_END
707
708// Used by dll.cpp to ensure objects are in dll.o, and not strciphr.o.
709#ifdef CRYPTOPP_MANUALLY_INSTANTIATE_TEMPLATES
710# include "strciphr.cpp"
711#endif
712
713NAMESPACE_BEGIN(CryptoPP)
714
717
721
722NAMESPACE_END
723
724#if CRYPTOPP_MSC_VERSION
725# pragma warning(pop)
726#endif
727
728#endif
Standard names for retrieving values by name when working with NameValuePairs.
Access a stream cipher policy object.
Definition: strciphr.h:50
Base class for additive stream ciphers with SymmetricCipher interface.
Definition: strciphr.h:298
unsigned int OptimalBlockSize() const
Provides number of ideal bytes to process.
Definition: strciphr.h:334
void ProcessData(byte *outString, const byte *inString, size_t length)
Apply keystream to data.
bool IsRandomAccess() const
Flag indicating random access.
Definition: strciphr.h:358
void GenerateBlock(byte *output, size_t size)
Generate random array of bytes.
unsigned int GetOptimalNextBlockSize() const
Provides number of ideal bytes to process.
Definition: strciphr.h:340
void Seek(lword position)
Seeks to a random position in the stream.
std::string AlgorithmProvider() const
Retrieve the provider of this algorithm.
Definition: strciphr.h:379
void Resynchronize(const byte *iv, int length=-1)
Resynchronize the cipher.
bool IsSelfInverting() const
Determines if the cipher is self inverting.
Definition: strciphr.h:349
bool IsForwardTransformation() const
Determines if the cipher is a forward transformation.
Definition: strciphr.h:353
unsigned int OptimalDataAlignment() const
Provides number of ideal data alignment.
Definition: strciphr.h:345
Base class information.
Definition: simple.h:40
SecBlock using AllocatorWithCleanup<byte, true> typedef.
Definition: secblock.h:1230
Policy object for feeback based stream ciphers.
Definition: strciphr.h:398
virtual void Iterate(byte *output, const byte *input, CipherDir dir, size_t iterationCount)
Iterate the cipher.
Definition: strciphr.h:430
virtual unsigned int GetAlignment() const =0
Provides data alignment requirements.
virtual unsigned int GetBytesPerIteration() const =0
Provides number of bytes operated upon during an iteration.
virtual byte * GetRegisterBegin()=0
Access the feedback register.
virtual void TransformRegister()=0
TODO.
virtual void CipherSetKey(const NameValuePairs &params, const byte *key, size_t length)=0
Key the cipher.
virtual std::string AlgorithmProvider() const
Retrieve the provider of this algorithm.
Definition: strciphr.h:462
virtual void CipherResynchronize(const byte *iv, size_t length)
Resynchronize the cipher.
Definition: strciphr.h:444
virtual bool CanIterate() const
Flag indicating iteration support.
Definition: strciphr.h:422
Base class for feedback based stream ciphers with SymmetricCipher interface.
Definition: strciphr.h:563
std::string AlgorithmProvider() const
Retrieve the provider of this algorithm.
Definition: strciphr.h:628
unsigned int OptimalBlockSize() const
Provides number of ideal bytes to process.
Definition: strciphr.h:592
unsigned int OptimalDataAlignment() const
Provides number of ideal data alignment.
Definition: strciphr.h:603
bool IsRandomAccess() const
Flag indicating random access.
Definition: strciphr.h:608
void Resynchronize(const byte *iv, int length=-1)
Resynchronize the cipher.
unsigned int GetOptimalNextBlockSize() const
Provides number of ideal bytes to process.
Definition: strciphr.h:598
bool IsSelfInverting() const
Determines if the cipher is self inverting.
Definition: strciphr.h:612
void ProcessData(byte *outString, const byte *inString, size_t length)
Apply keystream to data.
Base class for feedback based stream ciphers in the reverse direction with SymmetricCipher interface.
Definition: strciphr.h:655
Base class for feedback based stream ciphers in the forward direction with SymmetricCipher interface.
Definition: strciphr.h:646
Base class for feedback based stream ciphers with a mandatory block size.
Definition: strciphr.h:664
Interface for cloning objects.
Definition: cryptlib.h:585
Stream cipher policy object.
Definition: strciphr.h:65
Base class for all exceptions thrown by the library.
Definition: cryptlib.h:159
@ OTHER_ERROR
Some other error occurred not belonging to other categories.
Definition: cryptlib.h:177
Interface for retrieving values given their names.
Definition: cryptlib.h:322
A method was called which was not implemented.
Definition: cryptlib.h:233
Interface for random number generators.
Definition: cryptlib.h:1435
SymmetricCipher implementation.
Definition: strciphr.h:675
Clonable * Clone() const
Clone a SymmetricCipher.
Definition: strciphr.h:703
SymmetricCipherFinal()
Construct a stream cipher.
Definition: strciphr.h:680
SymmetricCipherFinal(const byte *key, size_t length, const byte *iv)
Construct a stream cipher.
Definition: strciphr.h:698
SymmetricCipherFinal(const byte *key, size_t length)
Construct a stream cipher.
Definition: strciphr.h:691
SymmetricCipherFinal(const byte *key)
Construct a stream cipher.
Definition: strciphr.h:685
Interface for one direction (encryption or decryption) of a stream cipher or cipher mode.
Definition: cryptlib.h:1291
Library configuration file.
#define CRYPTOPP_DLL_TEMPLATE_CLASS
Instantiate templates in a dynamic library.
Definition: config_dll.h:72
word64 lword
Large word type.
Definition: config_int.h:158
Abstract base classes that provide a uniform interface to this library.
CipherDir
Specifies a direction for a cipher to operate.
Definition: cryptlib.h:123
@ ENCRYPTION
the cipher is performing encryption
Definition: cryptlib.h:125
byte ByteReverse(byte value)
Reverses bytes in a 8-bit value.
Definition: misc.h:2021
bool NativeByteOrderIs(ByteOrder order)
Determines whether order follows native byte ordering.
Definition: misc.h:1271
bool IsAlignedOn(const void *ptr, unsigned int alignment)
Determines whether ptr is aligned to a minimum value.
Definition: misc.h:1226
PTR PtrAdd(PTR pointer, OFF offset)
Create a pointer with an offset.
Definition: misc.h:386
Crypto++ library namespace.
Classes and functions for secure memory allocations.
Classes and functions for implementing secret key algorithms.
KeystreamOperation
Keystream operation flags.
Definition: strciphr.h:88
@ XOR_KEYSTREAM
XOR the input buffer and keystream, write to the output buffer.
Definition: strciphr.h:94
@ WRITE_KEYSTREAM
Wirte the keystream to the output buffer, input is NULL.
Definition: strciphr.h:90
@ XOR_KEYSTREAM_BOTH_ALIGNED
XOR the aligned input buffer and keystream, write to the aligned output buffer.
Definition: strciphr.h:100
@ XOR_KEYSTREAM_INPUT_ALIGNED
XOR the aligned input buffer and keystream, write to the output buffer.
Definition: strciphr.h:96
@ XOR_KEYSTREAM_OUTPUT_ALIGNED
XOR the input buffer and keystream, write to the aligned output buffer.
Definition: strciphr.h:98
@ WRITE_KEYSTREAM_ALIGNED
Wirte the keystream to the aligned output buffer, input is NULL.
Definition: strciphr.h:92
KeystreamOperationFlags
Keystream operation flags.
Definition: strciphr.h:76
@ INPUT_NULL
Input buffer is NULL.
Definition: strciphr.h:82
@ INPUT_ALIGNED
Input buffer is aligned.
Definition: strciphr.h:80
@ OUTPUT_ALIGNED
Output buffer is aligned.
Definition: strciphr.h:78
Policy object for additive stream ciphers.
Definition: strciphr.h:105
virtual bool CanOperateKeystream() const
Flag indicating.
Definition: strciphr.h:139
virtual std::string AlgorithmProvider() const
Retrieve the provider of this algorithm.
Definition: strciphr.h:192
virtual unsigned int GetAlignment() const
Provides data alignment requirements.
Definition: strciphr.h:112
virtual unsigned int GetOptimalBlockSize() const
Provides number of ideal bytes to process.
Definition: strciphr.h:123
virtual unsigned int GetBytesPerIteration() const =0
Provides number of bytes operated upon during an iteration.
virtual void SeekToIteration(lword iterationCount)
Seeks to a random position in the stream.
Definition: strciphr.h:174
virtual void CipherSetKey(const NameValuePairs &params, const byte *key, size_t length)=0
Key the cipher.
virtual unsigned int GetIterationsToBuffer() const =0
Provides buffer size based on iterations.
virtual bool CipherIsRandomAccess() const =0
Flag indicating random access.
virtual void CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length)
Resynchronize the cipher.
Definition: strciphr.h:163
virtual void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount)
Operates the keystream.
Definition: strciphr.h:149
virtual void WriteKeystream(byte *keystream, size_t iterationCount)
Generate the keystream.
Definition: strciphr.h:133
Base class for additive stream ciphers.
Definition: strciphr.h:202
unsigned int GetBytesPerIteration() const
Provides number of bytes operated upon during an iteration.
Definition: strciphr.h:225
bool CanOperateKeystream() const
Flag indicating.
Definition: strciphr.h:235
unsigned int GetAlignment() const
Provides data alignment requirements.
Definition: strciphr.h:220
virtual void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount)=0
Operates the keystream.
WT WordType
Word type for the cipher.
Definition: strciphr.h:204
unsigned int GetIterationsToBuffer() const
Provides buffer size based on iterations.
Definition: strciphr.h:229
Provides alternate access to a feedback register.
Definition: strciphr.h:501
RegisterOutput & operator()(WordType &registerWord)
XOR feedback register with data.
Definition: strciphr.h:508
Base class for feedback based stream ciphers.
Definition: strciphr.h:471
unsigned int GetAlignment() const
Provides data alignment requirements.
Definition: strciphr.h:480
bool CanIterate() const
Flag indicating iteration support.
Definition: strciphr.h:489
void TransformRegister()
Perform one iteration in the forward direction.
Definition: strciphr.h:492
unsigned int GetBytesPerIteration() const
Provides number of bytes operated upon during an iteration.
Definition: strciphr.h:485
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:68