strciphr.h 32 KB

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