Security Scol plugin
strciphr.h
Go to the documentation of this file.
1// strciphr.h - originally written and placed in the public domain by Wei Dai
2
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
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
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
84
102
104struct CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AdditiveCipherAbstractPolicy
105{
107
112 virtual unsigned int GetAlignment() const {return 1;}
113
117 virtual unsigned int GetBytesPerIteration() const =0;
118
123 virtual unsigned int GetOptimalBlockSize() const {return GetBytesPerIteration();}
124
127 virtual unsigned int GetIterationsToBuffer() const =0;
128
133 virtual void WriteKeystream(byte *keystream, size_t iterationCount)
134 {OperateKeystream(KeystreamOperation(INPUT_NULL | static_cast<KeystreamOperationFlags>(IsAlignedOn(keystream, GetAlignment()))), keystream, NULLPTR, iterationCount);}
135
139 virtual bool CanOperateKeystream() const {return false;}
140
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
157 virtual void CipherSetKey(const NameValuePairs &params, const byte *key, size_t length) =0;
158
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
170 virtual bool CipherIsRandomAccess() const =0;
171
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
192 virtual std::string AlgorithmProvider() const { return "C++"; }
193};
194
200template <typename WT, unsigned int W, unsigned int X = 1, class BASE = AdditiveCipherAbstractPolicy>
201struct CRYPTOPP_NO_VTABLE AdditiveCipherConcretePolicy : public BASE
202{
204 typedef WT WordType;
205
211 CRYPTOPP_CONSTANT(BYTES_PER_ITERATION = sizeof(WordType) * W);
212
214
220 unsigned int GetAlignment() const {return GetAlignmentOf<WordType>();}
221
225 unsigned int GetBytesPerIteration() const {return BYTES_PER_ITERATION;}
226
229 unsigned int GetIterationsToBuffer() const {return X;}
230
235 bool CanOperateKeystream() const {return true;}
236
245 virtual void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount) =0;
246};
247
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
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
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
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
308 void GenerateBlock(byte *output, size_t size);
309
329 void ProcessData(byte *outString, const byte *inString, size_t length);
330
334 void Resynchronize(const byte *iv, int length=-1);
335
340 unsigned int OptimalBlockSize() const {return this->GetPolicy().GetOptimalBlockSize();}
341
346 unsigned int GetOptimalNextBlockSize() const {return (unsigned int)this->m_leftOver;}
347
351 unsigned int OptimalDataAlignment() const {return this->GetPolicy().GetAlignment();}
352
355 bool IsSelfInverting() const {return true;}
356
359 bool IsForwardTransformation() const {return true;}
360
364 bool IsRandomAccess() const {return this->GetPolicy().CipherIsRandomAccess();}
365
369 void Seek(lword position);
370
385 std::string AlgorithmProvider() const { return this->GetPolicy().AlgorithmProvider(); }
386
387 typedef typename BASE::PolicyInterface PolicyInterface;
388
389protected:
390 void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params);
391
392 unsigned int GetBufferByteSize(const PolicyInterface &policy) const {return policy.GetBytesPerIteration() * policy.GetIterationsToBuffer();}
393
394 inline byte * KeystreamBufferBegin() {return this->m_buffer.data();}
395 inline byte * KeystreamBufferEnd() {return (PtrAdd(this->m_buffer.data(), this->m_buffer.size()));}
396
397 AlignedSecByteBlock m_buffer;
398 size_t m_leftOver;
399};
400
402class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CFB_CipherAbstractPolicy
403{
404public:
405 virtual ~CFB_CipherAbstractPolicy() {}
406
411 virtual unsigned int GetAlignment() const =0;
412
416 virtual unsigned int GetBytesPerIteration() const =0;
417
420 virtual byte * GetRegisterBegin() =0;
421
423 virtual void TransformRegister() =0;
424
427 virtual bool CanIterate() const {return false;}
428
435 virtual void Iterate(byte *output, const byte *input, CipherDir dir, size_t iterationCount)
436 {CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(dir);
437 CRYPTOPP_UNUSED(iterationCount); CRYPTOPP_ASSERT(false);
438 throw Exception(Exception::OTHER_ERROR, "SimpleKeyingInterface: unexpected error");}
439
444 virtual void CipherSetKey(const NameValuePairs &params, const byte *key, size_t length) =0;
445
449 virtual void CipherResynchronize(const byte *iv, size_t length)
450 {CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(length);
451 throw NotImplemented("SimpleKeyingInterface: this object doesn't support resynchronization");}
452
467 virtual std::string AlgorithmProvider() const { return "C++"; }
468};
469
474template <typename WT, unsigned int W, class BASE = CFB_CipherAbstractPolicy>
475struct CRYPTOPP_NO_VTABLE CFB_CipherConcretePolicy : public BASE
476{
477 typedef WT WordType;
478
479 virtual ~CFB_CipherConcretePolicy() {}
480
485 unsigned int GetAlignment() const {return sizeof(WordType);}
486
490 unsigned int GetBytesPerIteration() const {return sizeof(WordType) * W;}
491
494 bool CanIterate() const {return true;}
495
497 void TransformRegister() {this->Iterate(NULLPTR, NULLPTR, ENCRYPTION, 1);}
498
504 template <class B>
506 {
507 RegisterOutput(byte *output, const byte *input, CipherDir dir)
508 : m_output(output), m_input(input), m_dir(dir) {}
509
513 inline RegisterOutput& operator()(WordType &registerWord)
514 {
515 //CRYPTOPP_ASSERT(IsAligned<WordType>(m_output));
516 //CRYPTOPP_ASSERT(IsAligned<WordType>(m_input));
517
518 if (!NativeByteOrderIs(B::ToEnum()))
519 registerWord = ByteReverse(registerWord);
520
521 if (m_dir == ENCRYPTION)
522 {
523 if (m_input == NULLPTR)
524 {
525 CRYPTOPP_ASSERT(m_output == NULLPTR);
526 }
527 else
528 {
529 // WordType ct = *(const WordType *)m_input ^ registerWord;
530 WordType ct = GetWord<WordType>(false, NativeByteOrder::ToEnum(), m_input) ^ registerWord;
531 registerWord = ct;
532
533 // *(WordType*)m_output = ct;
534 PutWord<WordType>(false, NativeByteOrder::ToEnum(), m_output, ct);
535
536 m_input += sizeof(WordType);
537 m_output += sizeof(WordType);
538 }
539 }
540 else
541 {
542 // WordType ct = *(const WordType *)m_input;
543 WordType ct = GetWord<WordType>(false, NativeByteOrder::ToEnum(), m_input);
544
545 // *(WordType*)m_output = registerWord ^ ct;
546 PutWord<WordType>(false, NativeByteOrder::ToEnum(), m_output, registerWord ^ ct);
547 registerWord = ct;
548
549 m_input += sizeof(WordType);
550 m_output += sizeof(WordType);
551 }
552
553 // registerWord is left unreversed so it can be xor-ed with further input
554
555 return *this;
556 }
557
558 byte *m_output;
559 const byte *m_input;
560 CipherDir m_dir;
561 };
562};
563
566template <class BASE>
567class CRYPTOPP_NO_VTABLE CFB_CipherTemplate : public BASE
568{
569public:
570 virtual ~CFB_CipherTemplate() {}
571 CFB_CipherTemplate() : m_leftOver(0) {}
572
592 void ProcessData(byte *outString, const byte *inString, size_t length);
593
597 void Resynchronize(const byte *iv, int length=-1);
598
603 unsigned int OptimalBlockSize() const {return this->GetPolicy().GetBytesPerIteration();}
604
609 unsigned int GetOptimalNextBlockSize() const {return (unsigned int)m_leftOver;}
610
614 unsigned int OptimalDataAlignment() const {return this->GetPolicy().GetAlignment();}
615
619 bool IsRandomAccess() const {return false;}
620
623 bool IsSelfInverting() const {return false;}
624
639 std::string AlgorithmProvider() const { return this->GetPolicy().AlgorithmProvider(); }
640
641 typedef typename BASE::PolicyInterface PolicyInterface;
642
643protected:
644 virtual void CombineMessageAndShiftRegister(byte *output, byte *reg, const byte *message, size_t length) =0;
645
646 void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params);
647
648 size_t m_leftOver;
649};
650
653template <class BASE = AbstractPolicyHolder<CFB_CipherAbstractPolicy, SymmetricCipher> >
654class CRYPTOPP_NO_VTABLE CFB_EncryptionTemplate : public CFB_CipherTemplate<BASE>
655{
656 bool IsForwardTransformation() const {return true;}
657 void CombineMessageAndShiftRegister(byte *output, byte *reg, const byte *message, size_t length);
658};
659
662template <class BASE = AbstractPolicyHolder<CFB_CipherAbstractPolicy, SymmetricCipher> >
663class CRYPTOPP_NO_VTABLE CFB_DecryptionTemplate : public CFB_CipherTemplate<BASE>
664{
665 bool IsForwardTransformation() const {return false;}
666 void CombineMessageAndShiftRegister(byte *output, byte *reg, const byte *message, size_t length);
667};
668
671template <class BASE>
672class CFB_RequireFullDataBlocks : public BASE
673{
674public:
675 unsigned int MandatoryBlockSize() const {return this->OptimalBlockSize();}
676};
677
682template <class BASE, class INFO = BASE>
683class SymmetricCipherFinal : public AlgorithmImpl<SimpleKeyingInterfaceImpl<BASE, INFO>, INFO>
684{
685public:
686 virtual ~SymmetricCipherFinal() {}
687
690
694 SymmetricCipherFinal(const byte *key)
695 {this->SetKey(key, this->DEFAULT_KEYLENGTH);}
696
700 SymmetricCipherFinal(const byte *key, size_t length)
701 {this->SetKey(key, length);}
702
707 SymmetricCipherFinal(const byte *key, size_t length, const byte *iv)
708 {this->SetKeyWithIV(key, length, iv);}
709
712 Clonable * Clone() const {return static_cast<SymmetricCipher *>(new SymmetricCipherFinal<BASE, INFO>(*this));}
713};
714
715NAMESPACE_END
716
717// Used by dll.cpp to ensure objects are in dll.o, and not strciphr.o.
718#ifdef CRYPTOPP_MANUALLY_INSTANTIATE_TEMPLATES
719# include "strciphr.cpp"
720#endif
721
722NAMESPACE_BEGIN(CryptoPP)
723
726
730
731NAMESPACE_END
732
733#if CRYPTOPP_MSC_VERSION
734# pragma warning(pop)
735#endif
736
737#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:340
bool IsRandomAccess() const
Flag indicating random access.
Definition strciphr.h:364
unsigned int GetOptimalNextBlockSize() const
Provides number of ideal bytes to process.
Definition strciphr.h:346
std::string AlgorithmProvider() const
Retrieve the provider of this algorithm.
Definition strciphr.h:385
bool IsSelfInverting() const
Determines if the cipher is self inverting.
Definition strciphr.h:355
bool IsForwardTransformation() const
Determines if the cipher is a forward transformation.
Definition strciphr.h:359
unsigned int OptimalDataAlignment() const
Provides number of ideal data alignment.
Definition strciphr.h:351
Base class information.
Definition simple.h:40
Policy object for feedback based stream ciphers.
Definition strciphr.h:403
virtual void Iterate(byte *output, const byte *input, CipherDir dir, size_t iterationCount)
Iterate the cipher.
Definition strciphr.h:435
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:467
virtual void CipherResynchronize(const byte *iv, size_t length)
Resynchronize the cipher.
Definition strciphr.h:449
virtual bool CanIterate() const
Flag indicating iteration support.
Definition strciphr.h:427
Base class for feedback based stream ciphers with SymmetricCipher interface.
Definition strciphr.h:568
std::string AlgorithmProvider() const
Retrieve the provider of this algorithm.
Definition strciphr.h:639
unsigned int OptimalBlockSize() const
Provides number of ideal bytes to process.
Definition strciphr.h:603
unsigned int OptimalDataAlignment() const
Provides number of ideal data alignment.
Definition strciphr.h:614
bool IsRandomAccess() const
Flag indicating random access.
Definition strciphr.h:619
unsigned int GetOptimalNextBlockSize() const
Provides number of ideal bytes to process.
Definition strciphr.h:609
bool IsSelfInverting() const
Determines if the cipher is self inverting.
Definition strciphr.h:623
Base class for feedback based stream ciphers in the reverse direction with SymmetricCipher interface.
Definition strciphr.h:664
Base class for feedback based stream ciphers in the forward direction with SymmetricCipher interface.
Definition strciphr.h:655
Base class for feedback based stream ciphers with a mandatory block size.
Definition strciphr.h:673
Namespace containing NaCl library functions.
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:684
Clonable * Clone() const
Clone a SymmetricCipher.
Definition strciphr.h:712
SymmetricCipherFinal()
Construct a stream cipher.
Definition strciphr.h:689
SymmetricCipherFinal(const byte *key, size_t length, const byte *iv)
Construct a stream cipher.
Definition strciphr.h:707
SymmetricCipherFinal(const byte *key, size_t length)
Construct a stream cipher.
Definition strciphr.h:700
SymmetricCipherFinal(const byte *key)
Construct a stream cipher.
Definition strciphr.h:694
Interface for one direction (encryption or decryption) of a stream cipher or cipher mode.
Definition cryptlib.h:1291
Library configuration file.
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:2022
bool NativeByteOrderIs(ByteOrder order)
Determines whether order follows native byte ordering.
Definition misc.h:1272
bool IsAlignedOn(const void *ptr, unsigned int alignment)
Determines whether ptr is aligned to a minimum value.
Definition misc.h:1227
PTR PtrAdd(PTR pointer, OFF offset)
Create a pointer with an offset.
Definition misc.h:386
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
Write 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
Write 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
CRYPTOPP_CONSTANT(BYTES_PER_ITERATION=sizeof(WordType) *W)
Number of bytes for an iteration.
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:506
RegisterOutput & operator()(WordType &registerWord)
XOR feedback register with data.
Definition strciphr.h:513
Base class for feedback based stream ciphers.
Definition strciphr.h:476
unsigned int GetAlignment() const
Provides data alignment requirements.
Definition strciphr.h:485
bool CanIterate() const
Flag indicating iteration support.
Definition strciphr.h:494
void TransformRegister()
Perform one iteration in the forward direction.
Definition strciphr.h:497
unsigned int GetBytesPerIteration() const
Provides number of bytes operated upon during an iteration.
Definition strciphr.h:490