Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2116 lines
77 KiB

  1. // misc.h - written and placed in the public domain by Wei Dai
  2. //! \file misc.h
  3. //! \brief Utility functions for the Crypto++ library.
  4. #ifndef CRYPTOPP_MISC_H
  5. #define CRYPTOPP_MISC_H
  6. #include "config.h"
  7. #if !CRYPTOPP_DOXYGEN_PROCESSING
  8. #if CRYPTOPP_MSC_VERSION
  9. # pragma warning(push)
  10. # pragma warning(disable: 4146)
  11. # if (CRYPTOPP_MSC_VERSION >= 1400)
  12. # pragma warning(disable: 6326)
  13. # endif
  14. #endif
  15. #include "cryptlib.h"
  16. #include "stdcpp.h"
  17. #include "smartptr.h"
  18. #ifdef _MSC_VER
  19. #if _MSC_VER >= 1400
  20. // VC2005 workaround: disable declarations that conflict with winnt.h
  21. #define _interlockedbittestandset CRYPTOPP_DISABLED_INTRINSIC_1
  22. #define _interlockedbittestandreset CRYPTOPP_DISABLED_INTRINSIC_2
  23. #define _interlockedbittestandset64 CRYPTOPP_DISABLED_INTRINSIC_3
  24. #define _interlockedbittestandreset64 CRYPTOPP_DISABLED_INTRINSIC_4
  25. #include <intrin.h>
  26. #undef _interlockedbittestandset
  27. #undef _interlockedbittestandreset
  28. #undef _interlockedbittestandset64
  29. #undef _interlockedbittestandreset64
  30. #define CRYPTOPP_FAST_ROTATE(x) 1
  31. #elif _MSC_VER >= 1300
  32. #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32 | (x) == 64)
  33. #else
  34. #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32)
  35. #endif
  36. #elif (defined(__MWERKS__) && TARGET_CPU_PPC) || \
  37. (defined(__GNUC__) && (defined(_ARCH_PWR2) || defined(_ARCH_PWR) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || defined(_ARCH_COM)))
  38. #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32)
  39. #elif defined(__GNUC__) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86) // depend on GCC's peephole optimization to generate rotate instructions
  40. #define CRYPTOPP_FAST_ROTATE(x) 1
  41. #else
  42. #define CRYPTOPP_FAST_ROTATE(x) 0
  43. #endif
  44. #ifdef __BORLANDC__
  45. #include <mem.h>
  46. #endif
  47. // !KLUDGE! @FD This gets confused and tries to include
  48. // tier1/byteswap.h. We'll just fall back on the slower
  49. // routines.//#if defined(__GNUC__) && defined(__linux__)
  50. //#define CRYPTOPP_BYTESWAP_AVAILABLE
  51. //#include <byteswap.h>
  52. //#endif
  53. #endif // CRYPTOPP_DOXYGEN_PROCESSING
  54. #if CRYPTOPP_DOXYGEN_PROCESSING
  55. //! \brief The maximum value of a machine word
  56. //! \details SIZE_MAX provides the maximum value of a machine word. The value is
  57. //! \p 0xffffffff on 32-bit machines, and \p 0xffffffffffffffff on 64-bit machines.
  58. //! Internally, SIZE_MAX is defined as __SIZE_MAX__ if __SIZE_MAX__ is defined. If not
  59. //! defined, then SIZE_T_MAX is tried. If neither __SIZE_MAX__ nor SIZE_T_MAX is
  60. //! is defined, the library uses std::numeric_limits<size_t>::max(). The library
  61. //! prefers __SIZE_MAX__ because its a constexpr that is optimized well
  62. //! by all compilers. std::numeric_limits<size_t>::max() is \a not a constexpr,
  63. //! and it is \a not always optimized well.
  64. # define SIZE_MAX ...
  65. #else
  66. // Its amazing portability problems still plague this simple concept in 2015.
  67. // http://stackoverflow.com/questions/30472731/which-c-standard-header-defines-size-max
  68. // Avoid NOMINMAX macro on Windows. http://support.microsoft.com/en-us/kb/143208
  69. #ifndef SIZE_MAX
  70. # if defined(__SIZE_MAX__)
  71. # define SIZE_MAX __SIZE_MAX__
  72. # elif defined(SIZE_T_MAX)
  73. # define SIZE_MAX SIZE_T_MAX
  74. # else
  75. # define SIZE_MAX ((std::numeric_limits<size_t>::max)())
  76. # endif
  77. #endif
  78. #endif // CRYPTOPP_DOXYGEN_PROCESSING
  79. NAMESPACE_BEGIN(CryptoPP)
  80. // Forward declaration for IntToString specialization
  81. class Integer;
  82. // ************** compile-time assertion ***************
  83. #if CRYPTOPP_DOXYGEN_PROCESSING
  84. //! \brief Compile time assertion
  85. //! \param expr the expression to evaluate
  86. //! \details Asserts the expression expr though a dummy struct.
  87. #define CRYPTOPP_COMPILE_ASSERT(expr) ...
  88. #else // CRYPTOPP_DOXYGEN_PROCESSING
  89. template <bool b>
  90. struct CompileAssert
  91. {
  92. static char dummy[2*b-1];
  93. };
  94. //! \endif
  95. #define CRYPTOPP_COMPILE_ASSERT(assertion) CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, __LINE__)
  96. #if defined(CRYPTOPP_EXPORTS) || defined(CRYPTOPP_IMPORTS)
  97. #define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance)
  98. #else
  99. # if defined(__GNUC__)
  100. # define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \
  101. static CompileAssert<(assertion)> \
  102. CRYPTOPP_ASSERT_JOIN(cryptopp_assert_, instance) __attribute__ ((unused))
  103. # else
  104. # define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \
  105. static CompileAssert<(assertion)> \
  106. CRYPTOPP_ASSERT_JOIN(cryptopp_assert_, instance)
  107. # endif // __GNUC__
  108. #endif
  109. #define CRYPTOPP_ASSERT_JOIN(X, Y) CRYPTOPP_DO_ASSERT_JOIN(X, Y)
  110. #define CRYPTOPP_DO_ASSERT_JOIN(X, Y) X##Y
  111. #endif // CRYPTOPP_DOXYGEN_PROCESSING
  112. // ************** count elements in an array ***************
  113. #if CRYPTOPP_DOXYGEN_PROCESSING
  114. //! \brief Counts elements in an array
  115. //! \param arr an array of elements
  116. //! \details COUNTOF counts elements in an array. On Windows COUNTOF(x) is deinfed
  117. //! to <tt>_countof(x)</tt> to ensure correct results for pointers. Since the library code
  118. //! is cross-platform, Windows will ensure the safety on non-Windows platforms.
  119. //! \note COUNTOF does not produce correct results with pointers, and an array must be used.
  120. //! The library ensures correct application of COUNTOF by enlisting _countof on Windows
  121. //! platforms. Microsoft's _countof fails to compile using pointers.
  122. # define COUNTOF(arr)
  123. #else
  124. // VS2005 added _countof
  125. #ifndef COUNTOF
  126. # if defined(_MSC_VER) && (_MSC_VER >= 1400)
  127. # define COUNTOF(x) _countof(x)
  128. # else
  129. # define COUNTOF(x) (sizeof(x)/sizeof(x[0]))
  130. # endif
  131. #endif // COUNTOF
  132. #endif // CRYPTOPP_DOXYGEN_PROCESSING
  133. // ************** misc classes ***************
  134. #if !CRYPTOPP_DOXYGEN_PROCESSING
  135. class CRYPTOPP_DLL Empty
  136. {
  137. };
  138. template <class BASE1, class BASE2>
  139. class CRYPTOPP_NO_VTABLE TwoBases : public BASE1, public BASE2
  140. {
  141. };
  142. template <class BASE1, class BASE2, class BASE3>
  143. class CRYPTOPP_NO_VTABLE ThreeBases : public BASE1, public BASE2, public BASE3
  144. {
  145. };
  146. #endif // CRYPTOPP_DOXYGEN_PROCESSING
  147. //! \class ObjectHolder
  148. //! \tparam the class or type
  149. //! \brief Uses encapsulation to hide an object in derived classes
  150. //! \details The object T is declared as protected.
  151. template <class T>
  152. class ObjectHolder
  153. {
  154. protected:
  155. T m_object;
  156. };
  157. //! \class NotCopyable
  158. //! \brief Ensures an object is not copyable
  159. //! \details NotCopyable ensures an object is not copyable by making the
  160. //! copy constructor and assignment operator private. Deleters are not
  161. //! used under C++11.
  162. //! \sa Clonable class
  163. class NotCopyable
  164. {
  165. public:
  166. NotCopyable() {}
  167. private:
  168. NotCopyable(const NotCopyable &);
  169. void operator=(const NotCopyable &);
  170. };
  171. //! \class NewObject
  172. //! \brief An object factory function
  173. //! \details NewObject overloads operator()().
  174. template <class T>
  175. struct NewObject
  176. {
  177. T* operator()() const {return new T;}
  178. };
  179. #if CRYPTOPP_DOXYGEN_PROCESSING
  180. //! \brief A memory barrier
  181. //! \details MEMORY_BARRIER attempts to ensure reads and writes are completed
  182. //! in the absence of a language synchronization point. It is used by the
  183. //! Singleton class if the compiler supports it. The use is provided at the
  184. //! customary check points in a double-checked initialization.
  185. //! \details Internally, MEMORY_BARRIER uses <tt>intrinsic(_ReadWriteBarrier)</tt>,
  186. //! <tt>_ReadWriteBarrier()</tt> or <tt>__asm__("" ::: "memory")</tt>.
  187. #define MEMORY_BARRIER ...
  188. #else
  189. #if (_MSC_VER >= 1400)
  190. # pragma intrinsic(_ReadWriteBarrier)
  191. # define MEMORY_BARRIER() _ReadWriteBarrier()
  192. #elif defined(__INTEL_COMPILER)
  193. # define MEMORY_BARRIER() __memory_barrier()
  194. #elif defined(__GNUC__) || defined(__clang__)
  195. # define MEMORY_BARRIER() __asm__ __volatile__ ("" ::: "memory")
  196. #else
  197. # define MEMORY_BARRIER()
  198. #endif
  199. #endif // CRYPTOPP_DOXYGEN_PROCESSING
  200. //! \brief Restricts the instantiation of a class to one static object without locks
  201. //! \tparam T the class or type
  202. //! \tparam F the object factory for T
  203. //! \tparam instance the initiali instance count
  204. //! \details This class safely initializes a static object in a multithreaded environment
  205. //! without using locks (for portability). Note that if two threads call Ref() at the same
  206. //! time, they may get back different references, and one object may end up being memory
  207. //! leaked. This is by design.
  208. template <class T, class F = NewObject<T>, int instance=0>
  209. class Singleton
  210. {
  211. public:
  212. Singleton(F objectFactory = F()) : m_objectFactory(objectFactory) {}
  213. // prevent this function from being inlined
  214. CRYPTOPP_NOINLINE const T & Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const;
  215. private:
  216. F m_objectFactory;
  217. };
  218. //! \brief Return a reference to the inner Singleton object
  219. //! \details Ref() is used to create the object using the object factory. The
  220. //! object is only created once with the limitations discussed in the class documentation.
  221. template <class T, class F, int instance>
  222. const T & Singleton<T, F, instance>::Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const
  223. {
  224. static volatile simple_ptr<T> s_pObject;
  225. T *p = s_pObject.m_p;
  226. MEMORY_BARRIER();
  227. if (p)
  228. return *p;
  229. T *newObject = m_objectFactory();
  230. p = s_pObject.m_p;
  231. MEMORY_BARRIER();
  232. if (p)
  233. {
  234. delete newObject;
  235. return *p;
  236. }
  237. s_pObject.m_p = newObject;
  238. MEMORY_BARRIER();
  239. return *newObject;
  240. }
  241. // ************** misc functions ***************
  242. #if (!__STDC_WANT_SECURE_LIB__ && !defined(_MEMORY_S_DEFINED)) || defined(CRYPTOPP_WANT_SECURE_LIB)
  243. //! \brief Bounds checking replacement for memcpy()
  244. //! \param dest pointer to the desination memory block
  245. //! \param sizeInBytes the size of the desination memory block, in bytes
  246. //! \param src pointer to the source memory block
  247. //! \param count the size of the source memory block, in bytes
  248. //! \throws InvalidArgument
  249. //! \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially
  250. //! unsafe functions like memcpy(), strcpy() and memmove(). However,
  251. //! not all standard libraries provides them, like Glibc. The library's
  252. //! memcpy_s() is a near-drop in replacement. Its only a near-replacement
  253. //! because the library's version throws an InvalidArgument on a bounds violation.
  254. //! \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__.
  255. //! If __STDC_WANT_SECURE_LIB__ is \a not defined or defined to 0, then the library
  256. //! makes memcpy_s() and memmove_s() available. The library will also optionally
  257. //! make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined.
  258. //! <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default.
  259. //! \details memcpy_s() will assert the pointers src and dest are not NULL
  260. //! in debug builds. Passing NULL for either pointer is undefined behavior.
  261. inline void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
  262. {
  263. // Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55
  264. // Pointers must be valid; otherwise undefined behavior
  265. assert(dest != NULL); assert(src != NULL);
  266. // Destination buffer must be large enough to satsify request
  267. assert(sizeInBytes >= count);
  268. if (count > sizeInBytes)
  269. throw InvalidArgument("memcpy_s: buffer overflow");
  270. #if CRYPTOPP_MSC_VERSION
  271. # pragma warning(push)
  272. # pragma warning(disable: 4996)
  273. # if (CRYPTOPP_MSC_VERSION >= 1400)
  274. # pragma warning(disable: 6386)
  275. # endif
  276. #endif
  277. memcpy(dest, src, count);
  278. #if CRYPTOPP_MSC_VERSION
  279. # pragma warning(pop)
  280. #endif
  281. }
  282. //! \brief Bounds checking replacement for memmove()
  283. //! \param dest pointer to the desination memory block
  284. //! \param sizeInBytes the size of the desination memory block, in bytes
  285. //! \param src pointer to the source memory block
  286. //! \param count the size of the source memory block, in bytes
  287. //! \throws InvalidArgument
  288. //! \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially
  289. //! unsafe functions like memcpy(), strcpy() and memmove(). However,
  290. //! not all standard libraries provides them, like Glibc. The library's
  291. //! memmove_s() is a near-drop in replacement. Its only a near-replacement
  292. //! because the library's version throws an InvalidArgument on a bounds violation.
  293. //! \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__.
  294. //! If __STDC_WANT_SECURE_LIB__ is \a not defined or defined to 0, then the library
  295. //! makes memcpy_s() and memmove_s() available. The library will also optionally
  296. //! make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined.
  297. //! <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default.
  298. //! \details memmove_s() will assert the pointers src and dest are not NULL
  299. //! in debug builds. Passing NULL for either pointer is undefined behavior.
  300. inline void memmove_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
  301. {
  302. // Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55
  303. // Pointers must be valid; otherwise undefined behavior
  304. assert(dest != NULL); assert(src != NULL);
  305. // Destination buffer must be large enough to satsify request
  306. assert(sizeInBytes >= count);
  307. if (count > sizeInBytes)
  308. throw InvalidArgument("memmove_s: buffer overflow");
  309. #if CRYPTOPP_MSC_VERSION
  310. # pragma warning(push)
  311. # pragma warning(disable: 4996)
  312. # if (CRYPTOPP_MSC_VERSION >= 1400)
  313. # pragma warning(disable: 6386)
  314. # endif
  315. #endif
  316. memmove(dest, src, count);
  317. #if CRYPTOPP_MSC_VERSION
  318. # pragma warning(pop)
  319. #endif
  320. }
  321. #if __BORLANDC__ >= 0x620
  322. // C++Builder 2010 workaround: can't use std::memcpy_s because it doesn't allow 0 lengths
  323. # define memcpy_s CryptoPP::memcpy_s
  324. # define memmove_s CryptoPP::memmove_s
  325. #endif
  326. #endif // __STDC_WANT_SECURE_LIB__
  327. //! \brief Memory block initializer and eraser that attempts to survive optimizations
  328. //! \param ptr pointer to the memory block being written
  329. //! \param value the integer value to write for each byte
  330. //! \param num the size of the source memory block, in bytes
  331. //! \details Internally the function calls memset with the value value, and receives the
  332. //! return value from memset as a <tt>volatile</tt> pointer.
  333. inline void * memset_z(void *ptr, int value, size_t num)
  334. {
  335. // avoid extranous warning on GCC 4.3.2 Ubuntu 8.10
  336. #if CRYPTOPP_GCC_VERSION >= 30001
  337. if (__builtin_constant_p(num) && num==0)
  338. return ptr;
  339. #endif
  340. volatile void* x = memset(ptr, value, num);
  341. return const_cast<void*>(x);
  342. }
  343. //! \brief Replacement function for std::min
  344. //! \param a the first value
  345. //! \param b the second value
  346. //! \returns the minimum value based on a comparison of <tt>b \< a</tt> using <tt>operator\<</tt>
  347. //! \details STDMIN was provided because the library could not use std::min or std::max in MSVC60 or Cygwin 1.1.0
  348. template <class T> inline const T& STDMIN(const T& a, const T& b)
  349. {
  350. return b < a ? b : a;
  351. }
  352. //! \brief Replacement function for std::max
  353. //! \param a the first value
  354. //! \param b the second value
  355. //! \returns the minimum value based on a comparison of <tt>a \< b</tt> using <tt>operator\<</tt>
  356. //! \details STDMAX was provided because the library could not use std::min or std::max in MSVC60 or Cygwin 1.1.0
  357. template <class T> inline const T& STDMAX(const T& a, const T& b)
  358. {
  359. // can't use std::min or std::max in MSVC60 or Cygwin 1.1.0
  360. return a < b ? b : a;
  361. }
  362. #if CRYPTOPP_MSC_VERSION
  363. # pragma warning(push)
  364. # pragma warning(disable: 4389)
  365. #endif
  366. #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
  367. # pragma GCC diagnostic push
  368. # pragma GCC diagnostic ignored "-Wsign-compare"
  369. # if (CRYPTOPP_CLANG_VERSION >= 20800) || (CRYPTOPP_APPLE_CLANG_VERSION >= 30000)
  370. # pragma GCC diagnostic ignored "-Wtautological-compare"
  371. # elif (CRYPTOPP_GCC_VERSION >= 40300)
  372. # pragma GCC diagnostic ignored "-Wtype-limits"
  373. # endif
  374. #endif
  375. //! \brief Safe comparison of values that could be neagtive and incorrectly promoted
  376. //! \param a the first value
  377. //! \param b the second value
  378. //! \returns the minimum value based on a comparison a and b using <tt>operator&lt;</tt>.
  379. //! \details The comparison <tt>b \< a</tt> is performed and the value returned is a's type T1.
  380. template <class T1, class T2> inline const T1 UnsignedMin(const T1& a, const T2& b)
  381. {
  382. CRYPTOPP_COMPILE_ASSERT((sizeof(T1)<=sizeof(T2) && T2(-1)>0) || (sizeof(T1)>sizeof(T2) && T1(-1)>0));
  383. if (sizeof(T1)<=sizeof(T2))
  384. return b < (T2)a ? (T1)b : a;
  385. else
  386. return (T1)b < a ? (T1)b : a;
  387. }
  388. //! \brief Tests whether a conversion from → to is safe to perform
  389. //! \param from the first value
  390. //! \param to the second value
  391. //! \returns true if its safe to convert from into to, false otherwise.
  392. template <class T1, class T2>
  393. inline bool SafeConvert(T1 from, T2 &to)
  394. {
  395. to = (T2)from;
  396. if (from != to || (from > 0) != (to > 0))
  397. return false;
  398. return true;
  399. }
  400. //! \brief Converts a value to a string
  401. //! \param value the value to convert
  402. //! \param base the base to use during the conversion
  403. //! \returns the string representation of value in base.
  404. template <class T>
  405. std::string IntToString(T value, unsigned int base = 10)
  406. {
  407. // Hack... set the high bit for uppercase.
  408. static const unsigned int HIGH_BIT = (1U << 31);
  409. const char CH = !!(base & HIGH_BIT) ? 'A' : 'a';
  410. base &= ~HIGH_BIT;
  411. assert(base >= 2);
  412. if (value == 0)
  413. return "0";
  414. bool negate = false;
  415. if (value < 0)
  416. {
  417. negate = true;
  418. value = 0-value; // VC .NET does not like -a
  419. }
  420. std::string result;
  421. while (value > 0)
  422. {
  423. T digit = value % base;
  424. result = char((digit < 10 ? '0' : (CH - 10)) + digit) + result;
  425. value /= base;
  426. }
  427. if (negate)
  428. result = "-" + result;
  429. return result;
  430. }
  431. //! \brief Converts an unsigned value to a string
  432. //! \param value the value to convert
  433. //! \param base the base to use during the conversion
  434. //! \returns the string representation of value in base.
  435. //! \details this template function specialization was added to suppress
  436. //! Coverity findings on IntToString() with unsigned types.
  437. template <> CRYPTOPP_DLL
  438. std::string IntToString<unsigned long long>(unsigned long long value, unsigned int base);
  439. //! \brief Converts an Integer to a string
  440. //! \param value the Integer to convert
  441. //! \param base the base to use during the conversion
  442. //! \returns the string representation of value in base.
  443. //! \details This is a template specialization of IntToString(). Use it
  444. //! like IntToString():
  445. //! <pre>
  446. //! // Print integer in base 10
  447. //! Integer n...
  448. //! std::string s = IntToString(n, 10);
  449. //! </pre>
  450. //! \details The string is presented with lowercase letters by default. A
  451. //! hack is available to switch to uppercase letters without modifying
  452. //! the function signature.sha
  453. //! <pre>
  454. //! // Print integer in base 10, uppercase letters
  455. //! Integer n...
  456. //! const unsigned int UPPER = (1 << 31);
  457. //! std::string s = IntToString(n, (UPPER | 10));
  458. //! </pre>
  459. template <> CRYPTOPP_DLL
  460. std::string IntToString<Integer>(Integer value, unsigned int base);
  461. #if CRYPTOPP_MSC_VERSION
  462. # pragma warning(pop)
  463. #endif
  464. #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
  465. # pragma GCC diagnostic pop
  466. #endif
  467. #define RETURN_IF_NONZERO(x) size_t returnedValue = x; if (returnedValue) return returnedValue
  468. // this version of the macro is fastest on Pentium 3 and Pentium 4 with MSVC 6 SP5 w/ Processor Pack
  469. #define GETBYTE(x, y) (unsigned int)byte((x)>>(8*(y)))
  470. // these may be faster on other CPUs/compilers
  471. // #define GETBYTE(x, y) (unsigned int)(((x)>>(8*(y)))&255)
  472. // #define GETBYTE(x, y) (((byte *)&(x))[y])
  473. #define CRYPTOPP_GET_BYTE_AS_BYTE(x, y) byte((x)>>(8*(y)))
  474. //! \brief Returns the parity of a value
  475. //! \param value the value to provide the parity
  476. //! \returns 1 if the number 1-bits in the value is odd, 0 otherwise
  477. template <class T>
  478. unsigned int Parity(T value)
  479. {
  480. for (unsigned int i=8*sizeof(value)/2; i>0; i/=2)
  481. value ^= value >> i;
  482. return (unsigned int)value&1;
  483. }
  484. //! \brief Returns the number of 8-bit bytes or octets required for a value
  485. //! \param value the value to test
  486. //! \returns the minimum number of 8-bit bytes or octets required to represent a value
  487. template <class T>
  488. unsigned int BytePrecision(const T &value)
  489. {
  490. if (!value)
  491. return 0;
  492. unsigned int l=0, h=8*sizeof(value);
  493. while (h-l > 8)
  494. {
  495. unsigned int t = (l+h)/2;
  496. if (value >> t)
  497. l = t;
  498. else
  499. h = t;
  500. }
  501. return h/8;
  502. }
  503. //! \brief Returns the number of bits required for a value
  504. //! \param value the value to test
  505. //! \returns the maximum number of bits required to represent a value.
  506. template <class T>
  507. unsigned int BitPrecision(const T &value)
  508. {
  509. if (!value)
  510. return 0;
  511. unsigned int l=0, h=8*sizeof(value);
  512. while (h-l > 1)
  513. {
  514. unsigned int t = (l+h)/2;
  515. if (value >> t)
  516. l = t;
  517. else
  518. h = t;
  519. }
  520. return h;
  521. }
  522. //! Determines the number of trailing 0-bits in a value
  523. //! \param v the 32-bit value to test
  524. //! \returns the number of trailing 0-bits in v, starting at the least significant bit position
  525. //! \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least
  526. //! significant bit position. The return value is undefined if there are no 1-bits set in the value v.
  527. //! \note The function does \a not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position.
  528. inline unsigned int TrailingZeros(word32 v)
  529. {
  530. assert(v != 0);
  531. #if defined(__GNUC__) && CRYPTOPP_GCC_VERSION >= 30400
  532. return __builtin_ctz(v);
  533. #elif defined(_MSC_VER) && _MSC_VER >= 1400
  534. unsigned long result;
  535. _BitScanForward(&result, v);
  536. return result;
  537. #else
  538. // from http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup
  539. static const int MultiplyDeBruijnBitPosition[32] =
  540. {
  541. 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  542. 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
  543. };
  544. return MultiplyDeBruijnBitPosition[((word32)((v & -v) * 0x077CB531U)) >> 27];
  545. #endif
  546. }
  547. //! Determines the number of trailing 0-bits in a value
  548. //! \param v the 64-bit value to test
  549. //! \returns the number of trailing 0-bits in v, starting at the least significant bit position
  550. //! \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least
  551. //! significant bit position. The return value is undefined if there are no 1-bits set in the value v.
  552. //! \note The function does \a not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position.
  553. inline unsigned int TrailingZeros(word64 v)
  554. {
  555. assert(v != 0);
  556. #if defined(__GNUC__) && CRYPTOPP_GCC_VERSION >= 30400
  557. return __builtin_ctzll(v);
  558. #elif defined(_MSC_VER) && _MSC_VER >= 1400 && (defined(_M_X64) || defined(_M_IA64))
  559. unsigned long result;
  560. _BitScanForward64(&result, v);
  561. return result;
  562. #else
  563. return word32(v) ? TrailingZeros(word32(v)) : 32 + TrailingZeros(word32(v>>32));
  564. #endif
  565. }
  566. //! \brief Truncates the value to the specified number of bits.
  567. //! \param value the value to truncate or mask
  568. //! \param bits the number of bits to truncate or mask
  569. //! \returns the value truncated to the specified number of bits, starting at the least
  570. //! significant bit position
  571. //! \details This function masks the low-order bits of value and returns the result. The
  572. //! mask is created with <tt>(1 << bits) - 1</tt>.
  573. template <class T>
  574. inline T Crop(T value, size_t bits)
  575. {
  576. if (bits < 8*sizeof(value))
  577. return T(value & ((T(1) << bits) - 1));
  578. else
  579. return value;
  580. }
  581. //! \brief Returns the number of 8-bit bytes or octets required for the specified number of bits
  582. //! \param bitCount the number of bits
  583. //! \returns the minimum number of 8-bit bytes or octets required by bitCount
  584. //! \details BitsToBytes is effectively a ceiling function based on 8-bit bytes.
  585. inline size_t BitsToBytes(size_t bitCount)
  586. {
  587. return ((bitCount+7)/(8));
  588. }
  589. //! \brief Returns the number of words required for the specified number of bytes
  590. //! \param byteCount the number of bytes
  591. //! \returns the minimum number of words required by byteCount
  592. //! \details BytesToWords is effectively a ceiling function based on <tt>WORD_SIZE</tt>.
  593. //! <tt>WORD_SIZE</tt> is defined in config.h
  594. inline size_t BytesToWords(size_t byteCount)
  595. {
  596. return ((byteCount+WORD_SIZE-1)/WORD_SIZE);
  597. }
  598. //! \brief Returns the number of words required for the specified number of bits
  599. //! \param bitCount the number of bits
  600. //! \returns the minimum number of words required by bitCount
  601. //! \details BitsToWords is effectively a ceiling function based on <tt>WORD_BITS</tt>.
  602. //! <tt>WORD_BITS</tt> is defined in config.h
  603. inline size_t BitsToWords(size_t bitCount)
  604. {
  605. return ((bitCount+WORD_BITS-1)/(WORD_BITS));
  606. }
  607. //! \brief Returns the number of double words required for the specified number of bits
  608. //! \param bitCount the number of bits
  609. //! \returns the minimum number of double words required by bitCount
  610. //! \details BitsToDwords is effectively a ceiling function based on <tt>2*WORD_BITS</tt>.
  611. //! <tt>WORD_BITS</tt> is defined in config.h
  612. inline size_t BitsToDwords(size_t bitCount)
  613. {
  614. return ((bitCount+2*WORD_BITS-1)/(2*WORD_BITS));
  615. }
  616. //! Performs an XOR of a buffer with a mask
  617. //! \param buf the buffer to XOR with the mask
  618. //! \param mask the mask to XOR with the buffer
  619. //! \param count the size of the buffers, in bytes
  620. //! \details The function effectively visits each element in the buffers and performs
  621. //! <tt>buf[i] ^= mask[i]</tt>. buf and mask must be of equal size.
  622. CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *buf, const byte *mask, size_t count);
  623. //! Performs an XOR of an input buffer with a mask and stores the result in an output buffer
  624. //! \param output the destination buffer
  625. //! \param input the source buffer to XOR with the mask
  626. //! \param mask the mask buffer to XOR with the input buffer
  627. //! \param count the size of the buffers, in bytes
  628. //! \details The function effectively visits each element in the buffers and performs
  629. //! <tt>output[i] = input[i] ^ mask[i]</tt>. output, input and mask must be of equal size.
  630. CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *output, const byte *input, const byte *mask, size_t count);
  631. //! \brief Performs a near constant-time comparison of two equally sized buffers
  632. //! \param buf1 the first buffer
  633. //! \param buf2 the second buffer
  634. //! \param count the size of the buffers, in bytes
  635. //! \details The function effectively performs an XOR of the elements in two equally sized buffers
  636. //! and retruns a result based on the XOR operation. The function is near constant-time because
  637. //! CPU micro-code timings could affect the "constant-ness". Calling code is responsible for
  638. //! mitigating timing attacks if the buffers are \a not equally sized.
  639. CRYPTOPP_DLL bool CRYPTOPP_API VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count);
  640. //! \brief Tests whether a value is a power of 2
  641. //! \param value the value to test
  642. //! \returns true if value is a power of 2, false otherwise
  643. //! \details The function creates a mask of <tt>value - 1</tt> and returns the result of
  644. //! an AND operation compared to 0. If value is 0 or less than 0, then the function returns false.
  645. template <class T>
  646. inline bool IsPowerOf2(const T &value)
  647. {
  648. return value > 0 && (value & (value-1)) == 0;
  649. }
  650. //! \brief Tests whether the residue of a value is a power of 2
  651. //! \param a the value to test
  652. //! \param b the value to use to reduce \a to its residue
  653. //! \returns true if <tt>a\%b</tt> is a power of 2, false otherwise
  654. //! \details The function effectively creates a mask of <tt>b - 1</tt> and returns the result of an
  655. //! AND operation compared to 0. b must be a power of 2 or the result is undefined.
  656. template <class T1, class T2>
  657. inline T2 ModPowerOf2(const T1 &a, const T2 &b)
  658. {
  659. assert(IsPowerOf2(b));
  660. return T2(a) & (b-1);
  661. }
  662. //! \brief Rounds a value down to a multiple of a second value
  663. //! \param n the value to reduce
  664. //! \param m the value to reduce \n to to a multiple
  665. //! \returns the possibly unmodified value \n
  666. //! \details RoundDownToMultipleOf is effectively a floor function based on m. The function returns
  667. //! the value <tt>n - n\%m</tt>. If n is a multiple of m, then the original value is returned.
  668. template <class T1, class T2>
  669. inline T1 RoundDownToMultipleOf(const T1 &n, const T2 &m)
  670. {
  671. if (IsPowerOf2(m))
  672. return n - ModPowerOf2(n, m);
  673. else
  674. return n - n%m;
  675. }
  676. //! \brief Rounds a value up to a multiple of a second value
  677. //! \param n the value to reduce
  678. //! \param m the value to reduce \n to to a multiple
  679. //! \returns the possibly unmodified value \n
  680. //! \details RoundUpToMultipleOf is effectively a ceiling function based on m. The function
  681. //! returns the value <tt>n + n\%m</tt>. If n is a multiple of m, then the original value is
  682. //! returned. If the value n would overflow, then an InvalidArgument exception is thrown.
  683. template <class T1, class T2>
  684. inline T1 RoundUpToMultipleOf(const T1 &n, const T2 &m)
  685. {
  686. if (n > (SIZE_MAX/sizeof(T1))-m-1)
  687. throw InvalidArgument("RoundUpToMultipleOf: integer overflow");
  688. return RoundDownToMultipleOf(T1(n+m-1), m);
  689. }
  690. //! \brief Returns the minimum alignment requirements of a type
  691. //! \param dummy an unused Visual C++ 6.0 workaround
  692. //! \returns the minimum alignment requirements of a type, in bytes
  693. //! \details Internally the function calls C++11's alignof if available. If not available, the
  694. //! function uses compiler specific extensions such as __alignof and _alignof_. sizeof(T)
  695. //! is used if the others are not available. In all cases, if CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
  696. //! is defined, then the function returns 1.
  697. template <class T>
  698. inline unsigned int GetAlignmentOf(T *dummy=NULL) // VC60 workaround
  699. {
  700. // GCC 4.6 (circa 2008) and above aggressively uses vectorization.
  701. #if defined(CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS)
  702. if (sizeof(T) < 16)
  703. return 1;
  704. #endif
  705. CRYPTOPP_UNUSED(dummy);
  706. #if defined(CRYPTOPP_CXX11_ALIGNOF)
  707. return alignof(T);
  708. #elif (_MSC_VER >= 1300)
  709. return __alignof(T);
  710. #elif defined(__GNUC__)
  711. return __alignof__(T);
  712. #elif CRYPTOPP_BOOL_SLOW_WORD64
  713. return UnsignedMin(4U, sizeof(T));
  714. #else
  715. return sizeof(T);
  716. #endif
  717. }
  718. //! \brief Determines whether ptr is aligned to a minimum value
  719. //! \param ptr the pointer being checked for alignment
  720. //! \param alignment the alignment value to test the pointer against
  721. //! \returns true if ptr is aligned on at least align boundary
  722. //! \details Internally the function tests whether alignment is 1. If so, the function returns true.
  723. //! If not, then the function effectively performs a modular reduction and returns true if the residue is 0
  724. inline bool IsAlignedOn(const void *ptr, unsigned int alignment)
  725. {
  726. return alignment==1 || (IsPowerOf2(alignment) ? ModPowerOf2((size_t)ptr, alignment) == 0 : (size_t)ptr % alignment == 0);
  727. }
  728. //! \brief Determines whether ptr is minimally aligned
  729. //! \param ptr the pointer to check for alignment
  730. //! \param dummy an unused Visual C++ 6.0 workaround
  731. //! \returns true if ptr follows native byte ordering, false otherwise
  732. //! \details Internally the function calls IsAlignedOn with a second parameter of GetAlignmentOf<T>
  733. template <class T>
  734. inline bool IsAligned(const void *ptr, T *dummy=NULL) // VC60 workaround
  735. {
  736. CRYPTOPP_UNUSED(dummy);
  737. return IsAlignedOn(ptr, GetAlignmentOf<T>());
  738. }
  739. #if defined(IS_LITTLE_ENDIAN)
  740. typedef LittleEndian NativeByteOrder;
  741. #elif defined(IS_BIG_ENDIAN)
  742. typedef BigEndian NativeByteOrder;
  743. #else
  744. # error "Unable to determine endian-ness"
  745. #endif
  746. //! \brief Returns NativeByteOrder as an enumerated ByteOrder value
  747. //! \returns LittleEndian if the native byte order is little-endian, and BigEndian if the
  748. //! native byte order is big-endian
  749. //! \details NativeByteOrder is a typedef depending on the platform. If IS_LITTLE_ENDIAN is
  750. //! set in \headerfile config.h, then GetNativeByteOrder returns LittleEndian. If
  751. //! IS_BIG_ENDIAN is set, then GetNativeByteOrder returns BigEndian.
  752. //! \note There are other byte orders besides little- and big-endian, and they include bi-endian
  753. //! and PDP-endian. If a system is neither little-endian nor big-endian, then a compile time error occurs.
  754. inline ByteOrder GetNativeByteOrder()
  755. {
  756. return NativeByteOrder::ToEnum();
  757. }
  758. //! \brief Determines whether order follows native byte ordering
  759. //! \param order the ordering being tested against native byte ordering
  760. //! \returns true if order follows native byte ordering, false otherwise
  761. inline bool NativeByteOrderIs(ByteOrder order)
  762. {
  763. return order == GetNativeByteOrder();
  764. }
  765. //! \brief Performs a saturating subtract clamped at 0
  766. //! \param a the minuend
  767. //! \param b the subtrahend
  768. //! \returns the difference produced by the saturating subtract
  769. //! \details Saturating arithmetic restricts results to a fixed range. Results that are less than 0 are clamped at 0.
  770. //! \details Use of saturating arithmetic in places can be advantageous because it can
  771. //! avoid a branch by using an instruction like a conditional move (<tt>CMOVE</tt>).
  772. template <class T1, class T2>
  773. inline T1 SaturatingSubtract(const T1 &a, const T2 &b)
  774. {
  775. // Generated ASM of a typical clamp, http://gcc.gnu.org/ml/gcc-help/2014-10/msg00112.html
  776. return T1((a > b) ? (a - b) : 0);
  777. }
  778. //! \brief Performs a saturating subtract clamped at 1
  779. //! \param a the minuend
  780. //! \param b the subtrahend
  781. //! \returns the difference produced by the saturating subtract
  782. //! \details Saturating arithmetic restricts results to a fixed range. Results that are less than 1 are clamped at 1.
  783. //! \details Use of saturating arithmetic in places can be advantageous because it can
  784. //! avoid a branch by using an instruction like a conditional move (<tt>CMOVE</tt>).
  785. template <class T1, class T2>
  786. inline T1 SaturatingSubtract1(const T1 &a, const T2 &b)
  787. {
  788. // Generated ASM of a typical clamp, http://gcc.gnu.org/ml/gcc-help/2014-10/msg00112.html
  789. return T1((a > b) ? (a - b) : 1);
  790. }
  791. //! \brief Returns the direction the cipher is being operated
  792. //! \param obj the cipher object being queried
  793. //! \returns /p ENCRYPTION if the cipher obj is being operated in its forward direction,
  794. //! DECRYPTION otherwise
  795. //! \details ciphers can be operated in a "forward" direction (encryption) and a "reverse"
  796. //! direction (decryption). The operations do not have to be symmetric, meaning a second application
  797. //! of the transformation does not necessariy return the original message. That is, <tt>E(D(m))</tt>
  798. //! may not equal <tt>E(E(m))</tt>; and <tt>D(E(m))</tt> may not equal <tt>D(D(m))</tt>.
  799. template <class T>
  800. inline CipherDir GetCipherDir(const T &obj)
  801. {
  802. return obj.IsForwardTransformation() ? ENCRYPTION : DECRYPTION;
  803. }
  804. //! \brief Attempts to reclaim unused memory
  805. //! \throws bad_alloc
  806. //! \details In the normal course of running a program, a request for memory normally succeeds. If a
  807. //! call to AlignedAllocate or UnalignedAllocate fails, then CallNewHandler is called in
  808. //! an effort to recover. Internally, CallNewHandler calls set_new_handler(NULL) in an effort
  809. //! to free memory. There is no guarantee CallNewHandler will be able to procure more memory so
  810. //! an allocation succeeds. If the call to set_new_handler fails, then CallNewHandler throws
  811. //! a bad_alloc exception.
  812. CRYPTOPP_DLL void CRYPTOPP_API CallNewHandler();
  813. //! \brief Performs an addition with carry on a block of bytes
  814. //! \param inout the byte block
  815. //! \param size the size of the block, in bytes
  816. //! \details Performs an addition with carry by adding 1 on a block of bytes starting at the least
  817. //! significant byte. Once carry is 0, the function terminates and returns to the caller.
  818. //! \note The function is not constant time because it stops processing when the carry is 0.
  819. inline void IncrementCounterByOne(byte *inout, unsigned int size)
  820. {
  821. assert(inout != NULL); assert(size < INT_MAX);
  822. for (int i=int(size-1), carry=1; i>=0 && carry; i--)
  823. carry = !++inout[i];
  824. }
  825. //! \brief Performs an addition with carry on a block of bytes
  826. //! \param output the destination block of bytes
  827. //! \param input the source block of bytes
  828. //! \param size the size of the block
  829. //! \details Performs an addition with carry on a block of bytes starting at the least significant
  830. //! byte. Once carry is 0, the remaining bytes from input are copied to output using memcpy.
  831. //! \details The function is \a close to near-constant time because it operates on all the bytes in the blocks.
  832. inline void IncrementCounterByOne(byte *output, const byte *input, unsigned int size)
  833. {
  834. assert(output != NULL); assert(input != NULL); assert(size < INT_MAX);
  835. int i, carry;
  836. for (i=int(size-1), carry=1; i>=0 && carry; i--)
  837. carry = ((output[i] = input[i]+1) == 0);
  838. memcpy_s(output, size, input, i+1);
  839. }
  840. //! \brief Performs a branchless swap of values a and b if condition c is true
  841. //! \param c the condition to perform the swap
  842. //! \param a the first value
  843. //! \param b the second value
  844. template <class T>
  845. inline void ConditionalSwap(bool c, T &a, T &b)
  846. {
  847. T t = c * (a ^ b);
  848. a ^= t;
  849. b ^= t;
  850. }
  851. //! \brief Performs a branchless swap of pointers a and b if condition c is true
  852. //! \param c the condition to perform the swap
  853. //! \param a the first pointer
  854. //! \param b the second pointer
  855. template <class T>
  856. inline void ConditionalSwapPointers(bool c, T &a, T &b)
  857. {
  858. ptrdiff_t t = size_t(c) * (a - b);
  859. a -= t;
  860. b += t;
  861. }
  862. // see http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/protect-secrets.html
  863. // and https://www.securecoding.cert.org/confluence/display/cplusplus/MSC06-CPP.+Be+aware+of+compiler+optimization+when+dealing+with+sensitive+data
  864. //! \brief Sets each element of an array to 0
  865. //! \param buf an array of elements
  866. //! \param n the number of elements in the array
  867. //! \details The operation is effectively a wipe or zeroization. The operation attempts to survive optimizations and dead code removal
  868. template <class T>
  869. void SecureWipeBuffer(T *buf, size_t n)
  870. {
  871. // GCC 4.3.2 on Cygwin optimizes away the first store if this loop is done in the forward direction
  872. volatile T *p = buf+n;
  873. while (n--)
  874. *((volatile T*)(--p)) = 0;
  875. }
  876. #if (_MSC_VER >= 1400 || defined(__GNUC__)) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86)
  877. //! \brief Sets each byte of an array to 0
  878. //! \param buf an array of bytes
  879. //! \param n the number of elements in the array
  880. //! \details The operation is effectively a wipe or zeroization. The operation attempts to survive optimizations and dead code removal
  881. template<> inline void SecureWipeBuffer(byte *buf, size_t n)
  882. {
  883. volatile byte *p = buf;
  884. #ifdef __GNUC__
  885. asm volatile("rep stosb" : "+c"(n), "+D"(p) : "a"(0) : "memory");
  886. #else
  887. __stosb((byte *)(size_t)p, 0, n);
  888. #endif
  889. }
  890. //! \brief Sets each 16-bit element of an array to 0
  891. //! \param buf an array of 16-bit words
  892. //! \param n the number of elements in the array
  893. //! \details The operation is effectively a wipe or zeroization. The operation attempts to survive optimizations and dead code removal
  894. template<> inline void SecureWipeBuffer(word16 *buf, size_t n)
  895. {
  896. volatile word16 *p = buf;
  897. #ifdef __GNUC__
  898. asm volatile("rep stosw" : "+c"(n), "+D"(p) : "a"(0) : "memory");
  899. #else
  900. __stosw((word16 *)(size_t)p, 0, n);
  901. #endif
  902. }
  903. //! \brief Sets each 32-bit element of an array to 0
  904. //! \param buf an array of 32-bit words
  905. //! \param n the number of elements in the array
  906. //! \details The operation is effectively a wipe or zeroization. The operation attempts to survive optimizations and dead code removal
  907. template<> inline void SecureWipeBuffer(word32 *buf, size_t n)
  908. {
  909. volatile word32 *p = buf;
  910. #ifdef __GNUC__
  911. asm volatile("rep stosl" : "+c"(n), "+D"(p) : "a"(0) : "memory");
  912. #else
  913. __stosd((unsigned long *)(size_t)p, 0, n);
  914. #endif
  915. }
  916. //! \brief Sets each 64-bit element of an array to 0
  917. //! \param buf an array of 64-bit words
  918. //! \param n the number of elements in the array
  919. //! \details The operation is effectively a wipe or zeroization. The operation attempts to survive optimizations and dead code removal
  920. template<> inline void SecureWipeBuffer(word64 *buf, size_t n)
  921. {
  922. #if CRYPTOPP_BOOL_X64
  923. volatile word64 *p = buf;
  924. #ifdef __GNUC__
  925. asm volatile("rep stosq" : "+c"(n), "+D"(p) : "a"(0) : "memory");
  926. #else
  927. __stosq((word64 *)(size_t)p, 0, n);
  928. #endif
  929. #else
  930. SecureWipeBuffer((word32 *)buf, 2*n);
  931. #endif
  932. }
  933. #endif // #if (_MSC_VER >= 1400 || defined(__GNUC__)) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86)
  934. //! \brief Sets each element of an array to 0
  935. //! \param buf an array of elements
  936. //! \param n the number of elements in the array
  937. //! \details The operation is effectively a wipe or zeroization. The operation attempts to survive optimizations and dead code removal
  938. template <class T>
  939. inline void SecureWipeArray(T *buf, size_t n)
  940. {
  941. if (sizeof(T) % 8 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word64>() == 0)
  942. SecureWipeBuffer((word64 *)buf, n * (sizeof(T)/8));
  943. else if (sizeof(T) % 4 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word32>() == 0)
  944. SecureWipeBuffer((word32 *)buf, n * (sizeof(T)/4));
  945. else if (sizeof(T) % 2 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word16>() == 0)
  946. SecureWipeBuffer((word16 *)buf, n * (sizeof(T)/2));
  947. else
  948. SecureWipeBuffer((byte *)buf, n * sizeof(T));
  949. }
  950. //! \brief Converts a wide character C-string to a multibyte string
  951. //! \param str a C-string consiting of wide characters
  952. //! \param throwOnError specifies the function should throw an InvalidArgument exception on error
  953. //! \returns str converted to a multibyte string or an empty string.
  954. //! \details This function converts a wide string to a string using C++ wcstombs under the executing
  955. //! thread's locale. A locale must be set before using this function, and it can be set with setlocale.
  956. //! Upon success, the converted string is returned. Upon failure with throwOnError as false, the
  957. //! function returns an empty string. Upon failure with throwOnError as true, the function throws
  958. //! InvalidArgument exception.
  959. //! \note If you try to convert, say, the Chinese character for "bone" from UTF-16 (0x9AA8) to UTF-8
  960. //! (0xE9 0xAA 0xA8), then you should ensure the locales are available. If the locales are not available,
  961. //! then a 0x21 error is returned which eventually results in an InvalidArgument exception
  962. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  963. static inline std::string StringNarrow(const wchar_t *str, bool throwOnError = true)
  964. #else
  965. static std::string StringNarrow(const wchar_t *str, bool throwOnError = true)
  966. #endif
  967. {
  968. assert(str);
  969. std::string result;
  970. // Safer functions on Windows for C&A, https://github.com/weidai11/cryptopp/issues/55
  971. #if (CRYPTOPP_MSC_VERSION >= 1400)
  972. size_t len=0, size = 0;
  973. errno_t err = 0;
  974. //const wchar_t* ptr = str;
  975. //while (*ptr++) len++;
  976. len = wcslen(str)+1;
  977. err = wcstombs_s(&size, NULL, 0, str, len*sizeof(wchar_t));
  978. assert(err == 0);
  979. if (err != 0) {goto CONVERSION_ERROR;}
  980. result.resize(size);
  981. err = wcstombs_s(&size, &result[0], size, str, len*sizeof(wchar_t));
  982. assert(err == 0);
  983. if (err != 0)
  984. {
  985. CONVERSION_ERROR:
  986. if (throwOnError)
  987. throw InvalidArgument("StringNarrow: wcstombs_s() call failed with error " + IntToString(err));
  988. else
  989. return std::string();
  990. }
  991. // The safe routine's size includes the NULL.
  992. if (!result.empty() && result[size - 1] == '\0')
  993. result.erase(size - 1);
  994. #else
  995. size_t size = wcstombs(NULL, str, 0);
  996. assert(size != (size_t)-1);
  997. if (size == (size_t)-1) {goto CONVERSION_ERROR;}
  998. result.resize(size);
  999. size = wcstombs(&result[0], str, size);
  1000. assert(size != (size_t)-1);
  1001. if (size == (size_t)-1)
  1002. {
  1003. CONVERSION_ERROR:
  1004. if (throwOnError)
  1005. throw InvalidArgument("StringNarrow: wcstombs() call failed");
  1006. else
  1007. return std::string();
  1008. }
  1009. #endif
  1010. return result;
  1011. }
  1012. #ifdef CRYPTOPP_DOXYGEN_PROCESSING
  1013. //! \brief Allocates a buffer on 16-byte boundary
  1014. //! \param size the size of the buffer
  1015. //! \details AlignedAllocate is primarily used when the data will be proccessed by MMX and SSE2
  1016. //! instructions. The assembly language routines rely on the alignment. If the alignment is not
  1017. //! respected, then a SIGBUS is generated under Unix and an EXCEPTION_DATATYPE_MISALIGNMENT
  1018. //! is generated under Windows.
  1019. //! \note AlignedAllocate and AlignedDeallocate are available when CRYPTOPP_BOOL_ALIGN16 is
  1020. //! defined. CRYPTOPP_BOOL_ALIGN16 is defined in config.h
  1021. CRYPTOPP_DLL void* CRYPTOPP_API AlignedAllocate(size_t size);
  1022. //! \brief Frees a buffer allocated with AlignedAllocate
  1023. //! \param ptr the buffer to free
  1024. //! \note AlignedAllocate and AlignedDeallocate are available when CRYPTOPP_BOOL_ALIGN16 is
  1025. //! defined. CRYPTOPP_BOOL_ALIGN16 is defined in config.h
  1026. CRYPTOPP_DLL void CRYPTOPP_API AlignedDeallocate(void *ptr);
  1027. #endif // CRYPTOPP_DOXYGEN_PROCESSING
  1028. #if CRYPTOPP_BOOL_ALIGN16
  1029. CRYPTOPP_DLL void* CRYPTOPP_API AlignedAllocate(size_t size);
  1030. CRYPTOPP_DLL void CRYPTOPP_API AlignedDeallocate(void *ptr);
  1031. #endif // CRYPTOPP_BOOL_ALIGN16
  1032. //! \brief Allocates a buffer
  1033. //! \param size the size of the buffer
  1034. CRYPTOPP_DLL void * CRYPTOPP_API UnalignedAllocate(size_t size);
  1035. //! \brief Frees a buffer allocated with UnalignedAllocate
  1036. //! \param ptr the buffer to free
  1037. CRYPTOPP_DLL void CRYPTOPP_API UnalignedDeallocate(void *ptr);
  1038. // ************** rotate functions ***************
  1039. //! \brief Performs a left rotate
  1040. //! \param x the value to rotate
  1041. //! \param y the number of bit positions to rotate the value
  1042. //! \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits.
  1043. //! \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1044. //! Use rotlMod if the rotate amount y is outside the range.
  1045. //! \note rotlFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
  1046. //! than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
  1047. //! counterparts.
  1048. template <class T> inline T rotlFixed(T x, unsigned int y)
  1049. {
  1050. // Portable rotate that reduces to single instruction...
  1051. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
  1052. // https://software.intel.com/en-us/forums/topic/580884
  1053. // and https://llvm.org/bugs/show_bug.cgi?id=24226
  1054. static const unsigned int THIS_SIZE = sizeof(T)*8;
  1055. static const unsigned int MASK = THIS_SIZE-1;
  1056. assert(y < THIS_SIZE);
  1057. return T((x<<y)|(x>>(-y&MASK)));
  1058. }
  1059. //! \brief Performs a right rotate
  1060. //! \param x the value to rotate
  1061. //! \param y the number of bit positions to rotate the value
  1062. //! \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits.
  1063. //! \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1064. //! Use rotrMod if the rotate amount y is outside the range.
  1065. //! \note rotrFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
  1066. //! than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
  1067. //! counterparts.
  1068. template <class T> inline T rotrFixed(T x, unsigned int y)
  1069. {
  1070. // Portable rotate that reduces to single instruction...
  1071. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
  1072. // https://software.intel.com/en-us/forums/topic/580884
  1073. // and https://llvm.org/bugs/show_bug.cgi?id=24226
  1074. static const unsigned int THIS_SIZE = sizeof(T)*8;
  1075. static const unsigned int MASK = THIS_SIZE-1;
  1076. assert(y < THIS_SIZE);
  1077. return T((x >> y)|(x<<(-y&MASK)));
  1078. }
  1079. //! \brief Performs a left rotate
  1080. //! \param x the value to rotate
  1081. //! \param y the number of bit positions to rotate the value
  1082. //! \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits.
  1083. //! \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1084. //! Use rotlMod if the rotate amount y is outside the range.
  1085. //! \note rotlVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
  1086. //! than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
  1087. //! counterparts.
  1088. template <class T> inline T rotlVariable(T x, unsigned int y)
  1089. {
  1090. static const unsigned int THIS_SIZE = sizeof(T)*8;
  1091. static const unsigned int MASK = THIS_SIZE-1;
  1092. assert(y < THIS_SIZE);
  1093. return T((x<<y)|(x>>(-y&MASK)));
  1094. }
  1095. //! \brief Performs a right rotate
  1096. //! \param x the value to rotate
  1097. //! \param y the number of bit positions to rotate the value
  1098. //! \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits.
  1099. //! \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1100. //! Use rotrMod if the rotate amount y is outside the range.
  1101. //! \note rotrVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
  1102. //! than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
  1103. //! counterparts.
  1104. template <class T> inline T rotrVariable(T x, unsigned int y)
  1105. {
  1106. static const unsigned int THIS_SIZE = sizeof(T)*8;
  1107. static const unsigned int MASK = THIS_SIZE-1;
  1108. assert(y < THIS_SIZE);
  1109. return T((x>>y)|(x<<(-y&MASK)));
  1110. }
  1111. //! \brief Performs a left rotate
  1112. //! \param x the value to rotate
  1113. //! \param y the number of bit positions to rotate the value
  1114. //! \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits.
  1115. //! \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1116. //! \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>.
  1117. template <class T> inline T rotlMod(T x, unsigned int y)
  1118. {
  1119. static const unsigned int THIS_SIZE = sizeof(T)*8;
  1120. static const unsigned int MASK = THIS_SIZE-1;
  1121. return T((x<<(y&MASK))|(x>>(-y&MASK)));
  1122. }
  1123. //! \brief Performs a right rotate
  1124. //! \param x the value to rotate
  1125. //! \param y the number of bit positions to rotate the value
  1126. //! \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits.
  1127. //! \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1128. //! \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>.
  1129. template <class T> inline T rotrMod(T x, unsigned int y)
  1130. {
  1131. static const unsigned int THIS_SIZE = sizeof(T)*8;
  1132. static const unsigned int MASK = THIS_SIZE-1;
  1133. return T((x>>(y&MASK))|(x<<(-y&MASK)));
  1134. }
  1135. #ifdef _MSC_VER
  1136. //! \brief Performs a left rotate
  1137. //! \param x the 32-bit value to rotate
  1138. //! \param y the number of bit positions to rotate the value
  1139. //! \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by \headerfile
  1140. //! <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
  1141. //! <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1142. //! \note rotlFixed will assert in Debug builds if is outside the allowed range.
  1143. template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y)
  1144. {
  1145. // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
  1146. assert(y < 8*sizeof(x));
  1147. return y ? _lrotl(x, static_cast<byte>(y)) : x;
  1148. }
  1149. //! \brief Performs a right rotate
  1150. //! \param x the 32-bit value to rotate
  1151. //! \param y the number of bit positions to rotate the value
  1152. //! \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by \headerfile
  1153. //! <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
  1154. //! <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1155. //! \note rotrFixed will assert in Debug builds if is outside the allowed range.
  1156. template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y)
  1157. {
  1158. // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
  1159. assert(y < 8*sizeof(x));
  1160. return y ? _lrotr(x, static_cast<byte>(y)) : x;
  1161. }
  1162. //! \brief Performs a left rotate
  1163. //! \param x the 32-bit value to rotate
  1164. //! \param y the number of bit positions to rotate the value
  1165. //! \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by \headerfile
  1166. //! <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
  1167. //! <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1168. //! \note rotlVariable will assert in Debug builds if is outside the allowed range.
  1169. template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y)
  1170. {
  1171. assert(y < 8*sizeof(x));
  1172. return _lrotl(x, static_cast<byte>(y));
  1173. }
  1174. //! \brief Performs a right rotate
  1175. //! \param x the 32-bit value to rotate
  1176. //! \param y the number of bit positions to rotate the value
  1177. //! \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by \headerfile
  1178. //! <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
  1179. //! <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1180. //! \note rotrVariable will assert in Debug builds if is outside the allowed range.
  1181. template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y)
  1182. {
  1183. assert(y < 8*sizeof(x));
  1184. return _lrotr(x, static_cast<byte>(y));
  1185. }
  1186. //! \brief Performs a left rotate
  1187. //! \param x the 32-bit value to rotate
  1188. //! \param y the number of bit positions to rotate the value
  1189. //! \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by \headerfile
  1190. //! <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
  1191. //! <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1192. template<> inline word32 rotlMod<word32>(word32 x, unsigned int y)
  1193. {
  1194. y %= 8*sizeof(x);
  1195. return _lrotl(x, static_cast<byte>(y));
  1196. }
  1197. //! \brief Performs a right rotate
  1198. //! \param x the 32-bit value to rotate
  1199. //! \param y the number of bit positions to rotate the value
  1200. //! \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by \headerfile
  1201. //! <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
  1202. //! <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1203. template<> inline word32 rotrMod<word32>(word32 x, unsigned int y)
  1204. {
  1205. y %= 8*sizeof(x);
  1206. return _lrotr(x, static_cast<byte>(y));
  1207. }
  1208. #endif // #ifdef _MSC_VER
  1209. #if _MSC_VER >= 1300 && !defined(__INTEL_COMPILER)
  1210. // Intel C++ Compiler 10.0 calls a function instead of using the rotate instruction when using these instructions
  1211. //! \brief Performs a left rotate
  1212. //! \param x the 64-bit value to rotate
  1213. //! \param y the number of bit positions to rotate the value
  1214. //! \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by \headerfile
  1215. //! <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
  1216. //! <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1217. //! \note rotrFixed will assert in Debug builds if is outside the allowed range.
  1218. template<> inline word64 rotlFixed<word64>(word64 x, unsigned int y)
  1219. {
  1220. // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
  1221. assert(y < 8*sizeof(x));
  1222. return y ? _rotl64(x, static_cast<byte>(y)) : x;
  1223. }
  1224. //! \brief Performs a right rotate
  1225. //! \param x the 64-bit value to rotate
  1226. //! \param y the number of bit positions to rotate the value
  1227. //! \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by \headerfile
  1228. //! <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
  1229. //! <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1230. //! \note rotrFixed will assert in Debug builds if is outside the allowed range.
  1231. template<> inline word64 rotrFixed<word64>(word64 x, unsigned int y)
  1232. {
  1233. // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
  1234. assert(y < 8*sizeof(x));
  1235. return y ? _rotr64(x, static_cast<byte>(y)) : x;
  1236. }
  1237. //! \brief Performs a left rotate
  1238. //! \param x the 64-bit value to rotate
  1239. //! \param y the number of bit positions to rotate the value
  1240. //! \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by \headerfile
  1241. //! <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
  1242. //! <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1243. //! \note rotlVariable will assert in Debug builds if is outside the allowed range.
  1244. template<> inline word64 rotlVariable<word64>(word64 x, unsigned int y)
  1245. {
  1246. assert(y < 8*sizeof(x));
  1247. return _rotl64(x, static_cast<byte>(y));
  1248. }
  1249. //! \brief Performs a right rotate
  1250. //! \param x the 64-bit value to rotate
  1251. //! \param y the number of bit positions to rotate the value
  1252. //! \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by \headerfile
  1253. //! <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
  1254. //! <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1255. //! \note rotrVariable will assert in Debug builds if is outside the allowed range.
  1256. template<> inline word64 rotrVariable<word64>(word64 x, unsigned int y)
  1257. {
  1258. assert(y < 8*sizeof(x));
  1259. return y ? _rotr64(x, static_cast<byte>(y)) : x;
  1260. }
  1261. //! \brief Performs a left rotate
  1262. //! \param x the 64-bit value to rotate
  1263. //! \param y the number of bit positions to rotate the value
  1264. //! \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by \headerfile
  1265. //! <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
  1266. //! <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1267. template<> inline word64 rotlMod<word64>(word64 x, unsigned int y)
  1268. {
  1269. assert(y < 8*sizeof(x));
  1270. return y ? _rotl64(x, static_cast<byte>(y)) : x;
  1271. }
  1272. //! \brief Performs a right rotate
  1273. //! \param x the 64-bit value to rotate
  1274. //! \param y the number of bit positions to rotate the value
  1275. //! \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by \headerfile
  1276. //! <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
  1277. //! <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1278. template<> inline word64 rotrMod<word64>(word64 x, unsigned int y)
  1279. {
  1280. assert(y < 8*sizeof(x));
  1281. return y ? _rotr64(x, static_cast<byte>(y)) : x;
  1282. }
  1283. #endif // #if _MSC_VER >= 1310
  1284. #if _MSC_VER >= 1400 && !defined(__INTEL_COMPILER)
  1285. // Intel C++ Compiler 10.0 gives undefined externals with these
  1286. template<> inline word16 rotlFixed<word16>(word16 x, unsigned int y)
  1287. {
  1288. // Intrinsic, not bound to C/C++ language rules.
  1289. return _rotl16(x, static_cast<byte>(y));
  1290. }
  1291. template<> inline word16 rotrFixed<word16>(word16 x, unsigned int y)
  1292. {
  1293. // Intrinsic, not bound to C/C++ language rules.
  1294. return _rotr16(x, static_cast<byte>(y));
  1295. }
  1296. template<> inline word16 rotlVariable<word16>(word16 x, unsigned int y)
  1297. {
  1298. return _rotl16(x, static_cast<byte>(y));
  1299. }
  1300. template<> inline word16 rotrVariable<word16>(word16 x, unsigned int y)
  1301. {
  1302. return _rotr16(x, static_cast<byte>(y));
  1303. }
  1304. template<> inline word16 rotlMod<word16>(word16 x, unsigned int y)
  1305. {
  1306. return _rotl16(x, static_cast<byte>(y));
  1307. }
  1308. template<> inline word16 rotrMod<word16>(word16 x, unsigned int y)
  1309. {
  1310. return _rotr16(x, static_cast<byte>(y));
  1311. }
  1312. template<> inline byte rotlFixed<byte>(byte x, unsigned int y)
  1313. {
  1314. // Intrinsic, not bound to C/C++ language rules.
  1315. return _rotl8(x, static_cast<byte>(y));
  1316. }
  1317. template<> inline byte rotrFixed<byte>(byte x, unsigned int y)
  1318. {
  1319. // Intrinsic, not bound to C/C++ language rules.
  1320. return _rotr8(x, static_cast<byte>(y));
  1321. }
  1322. template<> inline byte rotlVariable<byte>(byte x, unsigned int y)
  1323. {
  1324. return _rotl8(x, static_cast<byte>(y));
  1325. }
  1326. template<> inline byte rotrVariable<byte>(byte x, unsigned int y)
  1327. {
  1328. return _rotr8(x, static_cast<byte>(y));
  1329. }
  1330. template<> inline byte rotlMod<byte>(byte x, unsigned int y)
  1331. {
  1332. return _rotl8(x, static_cast<byte>(y));
  1333. }
  1334. template<> inline byte rotrMod<byte>(byte x, unsigned int y)
  1335. {
  1336. return _rotr8(x, static_cast<byte>(y));
  1337. }
  1338. #endif // #if _MSC_VER >= 1400
  1339. #if (defined(__MWERKS__) && TARGET_CPU_PPC)
  1340. template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y)
  1341. {
  1342. assert(y < 32);
  1343. return y ? __rlwinm(x,y,0,31) : x;
  1344. }
  1345. template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y)
  1346. {
  1347. assert(y < 32);
  1348. return y ? __rlwinm(x,32-y,0,31) : x;
  1349. }
  1350. template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y)
  1351. {
  1352. assert(y < 32);
  1353. return (__rlwnm(x,y,0,31));
  1354. }
  1355. template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y)
  1356. {
  1357. assert(y < 32);
  1358. return (__rlwnm(x,32-y,0,31));
  1359. }
  1360. template<> inline word32 rotlMod<word32>(word32 x, unsigned int y)
  1361. {
  1362. return (__rlwnm(x,y,0,31));
  1363. }
  1364. template<> inline word32 rotrMod<word32>(word32 x, unsigned int y)
  1365. {
  1366. return (__rlwnm(x,32-y,0,31));
  1367. }
  1368. #endif // #if (defined(__MWERKS__) && TARGET_CPU_PPC)
  1369. // ************** endian reversal ***************
  1370. //! \brief Gets a byte from a value
  1371. //! \param order the ByteOrder of the value
  1372. //! \param value the value to retrieve the byte
  1373. //! \param index the location of the byte to retrieve
  1374. template <class T>
  1375. inline unsigned int GetByte(ByteOrder order, T value, unsigned int index)
  1376. {
  1377. if (order == LITTLE_ENDIAN_ORDER)
  1378. return GETBYTE(value, index);
  1379. else
  1380. return GETBYTE(value, sizeof(T)-index-1);
  1381. }
  1382. //! \brief Reverses bytes in a 8-bit value
  1383. //! \param value the 8-bit value to reverse
  1384. //! \note ByteReverse returns the value passed to it since there is nothing to reverse
  1385. inline byte ByteReverse(byte value)
  1386. {
  1387. return value;
  1388. }
  1389. //! \brief Reverses bytes in a 16-bit value
  1390. //! \brief Performs an endian reversal
  1391. //! \param value the 16-bit value to reverse
  1392. //! \details ByteReverse calls bswap if available. Otherwise the function performs a 8-bit rotate on the word16
  1393. inline word16 ByteReverse(word16 value)
  1394. {
  1395. #ifdef CRYPTOPP_BYTESWAP_AVAILABLE
  1396. return bswap_16(value);
  1397. #elif defined(_MSC_VER) && _MSC_VER >= 1300
  1398. return _byteswap_ushort(value);
  1399. #else
  1400. return rotlFixed(value, 8U);
  1401. #endif
  1402. }
  1403. //! \brief Reverses bytes in a 32-bit value
  1404. //! \brief Performs an endian reversal
  1405. //! \param value the 32-bit value to reverse
  1406. //! \details ByteReverse calls bswap if available. Otherwise the function uses a combination of rotates on the word32
  1407. inline word32 ByteReverse(word32 value)
  1408. {
  1409. #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
  1410. __asm__ ("bswap %0" : "=r" (value) : "0" (value));
  1411. return value;
  1412. #elif defined(CRYPTOPP_BYTESWAP_AVAILABLE)
  1413. return bswap_32(value);
  1414. #elif defined(__MWERKS__) && TARGET_CPU_PPC
  1415. return (word32)__lwbrx(&value,0);
  1416. #elif _MSC_VER >= 1400 || (_MSC_VER >= 1300 && !defined(_DLL))
  1417. return _byteswap_ulong(value);
  1418. #elif CRYPTOPP_FAST_ROTATE(32)
  1419. // 5 instructions with rotate instruction, 9 without
  1420. return (rotrFixed(value, 8U) & 0xff00ff00) | (rotlFixed(value, 8U) & 0x00ff00ff);
  1421. #else
  1422. // 6 instructions with rotate instruction, 8 without
  1423. value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
  1424. return rotlFixed(value, 16U);
  1425. #endif
  1426. }
  1427. //! \brief Reverses bytes in a 64-bit value
  1428. //! \brief Performs an endian reversal
  1429. //! \param value the 64-bit value to reverse
  1430. //! \details ByteReverse calls bswap if available. Otherwise the function uses a combination of rotates on the word64
  1431. inline word64 ByteReverse(word64 value)
  1432. {
  1433. #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE) && defined(__x86_64__)
  1434. __asm__ ("bswap %0" : "=r" (value) : "0" (value));
  1435. return value;
  1436. #elif defined(CRYPTOPP_BYTESWAP_AVAILABLE)
  1437. return bswap_64(value);
  1438. #elif defined(_MSC_VER) && _MSC_VER >= 1300
  1439. return _byteswap_uint64(value);
  1440. #elif CRYPTOPP_BOOL_SLOW_WORD64
  1441. return (word64(ByteReverse(word32(value))) << 32) | ByteReverse(word32(value>>32));
  1442. #else
  1443. value = ((value & W64LIT(0xFF00FF00FF00FF00)) >> 8) | ((value & W64LIT(0x00FF00FF00FF00FF)) << 8);
  1444. value = ((value & W64LIT(0xFFFF0000FFFF0000)) >> 16) | ((value & W64LIT(0x0000FFFF0000FFFF)) << 16);
  1445. return rotlFixed(value, 32U);
  1446. #endif
  1447. }
  1448. //! \brief Reverses bits in a 8-bit value
  1449. //! \param value the 8-bit value to reverse
  1450. //! \details BitReverse performs a combination of shifts on the byte
  1451. inline byte BitReverse(byte value)
  1452. {
  1453. value = ((value & 0xAA) >> 1) | ((value & 0x55) << 1);
  1454. value = ((value & 0xCC) >> 2) | ((value & 0x33) << 2);
  1455. return rotlFixed(value, 4U);
  1456. }
  1457. //! \brief Reverses bits in a 16-bit value
  1458. //! \param value the 16-bit value to reverse
  1459. //! \details BitReverse performs a combination of shifts on the word16
  1460. inline word16 BitReverse(word16 value)
  1461. {
  1462. value = ((value & 0xAAAA) >> 1) | ((value & 0x5555) << 1);
  1463. value = ((value & 0xCCCC) >> 2) | ((value & 0x3333) << 2);
  1464. value = ((value & 0xF0F0) >> 4) | ((value & 0x0F0F) << 4);
  1465. return ByteReverse(value);
  1466. }
  1467. //! \brief Reverses bits in a 32-bit value
  1468. //! \param value the 32-bit value to reverse
  1469. //! \details BitReverse performs a combination of shifts on the word32
  1470. inline word32 BitReverse(word32 value)
  1471. {
  1472. value = ((value & 0xAAAAAAAA) >> 1) | ((value & 0x55555555) << 1);
  1473. value = ((value & 0xCCCCCCCC) >> 2) | ((value & 0x33333333) << 2);
  1474. value = ((value & 0xF0F0F0F0) >> 4) | ((value & 0x0F0F0F0F) << 4);
  1475. return ByteReverse(value);
  1476. }
  1477. //! \brief Reverses bits in a 64-bit value
  1478. //! \param value the 64-bit value to reverse
  1479. //! \details BitReverse performs a combination of shifts on the word64
  1480. inline word64 BitReverse(word64 value)
  1481. {
  1482. #if CRYPTOPP_BOOL_SLOW_WORD64
  1483. return (word64(BitReverse(word32(value))) << 32) | BitReverse(word32(value>>32));
  1484. #else
  1485. value = ((value & W64LIT(0xAAAAAAAAAAAAAAAA)) >> 1) | ((value & W64LIT(0x5555555555555555)) << 1);
  1486. value = ((value & W64LIT(0xCCCCCCCCCCCCCCCC)) >> 2) | ((value & W64LIT(0x3333333333333333)) << 2);
  1487. value = ((value & W64LIT(0xF0F0F0F0F0F0F0F0)) >> 4) | ((value & W64LIT(0x0F0F0F0F0F0F0F0F)) << 4);
  1488. return ByteReverse(value);
  1489. #endif
  1490. }
  1491. //! \brief Reverses bits in a value
  1492. //! \param value the value to reverse
  1493. //! \details The template overload of BitReverse operates on signed and unsigned values.
  1494. //! Internally the size of T is checked, and then value is cast to a byte,
  1495. //! word16, word32 or word64. After the cast, the appropriate BitReverse
  1496. //! overload is called.
  1497. template <class T>
  1498. inline T BitReverse(T value)
  1499. {
  1500. if (sizeof(T) == 1)
  1501. return (T)BitReverse((byte)value);
  1502. else if (sizeof(T) == 2)
  1503. return (T)BitReverse((word16)value);
  1504. else if (sizeof(T) == 4)
  1505. return (T)BitReverse((word32)value);
  1506. else
  1507. {
  1508. assert(sizeof(T) == 8);
  1509. return (T)BitReverse((word64)value);
  1510. }
  1511. }
  1512. //! \brief Reverses bytes in a value depending upon endianess
  1513. //! \tparam T the class or type
  1514. //! \param order the ByteOrder the data is represented
  1515. //! \param value the value to conditionally reverse
  1516. //! \details Internally, the ConditionalByteReverse calls NativeByteOrderIs.
  1517. //! If order matches native byte order, then the original value is returned.
  1518. //! If not, then ByteReverse is called on the value before returning to the caller.
  1519. template <class T>
  1520. inline T ConditionalByteReverse(ByteOrder order, T value)
  1521. {
  1522. return NativeByteOrderIs(order) ? value : ByteReverse(value);
  1523. }
  1524. //! \brief Reverses bytes in an element among an array of elements
  1525. //! \tparam T the class or type
  1526. //! \param out the output array of elements
  1527. //! \param in the input array of elements
  1528. //! \param byteCount the byte count of the arrays
  1529. //! \details Internally, ByteReverse visits each element in the in array
  1530. //! calls ByteReverse on it, and writes the result to out.
  1531. //! \details ByteReverse does not process tail byes, or bytes that are
  1532. //! \a not part of a full element. If T is int (and int is 4 bytes), then
  1533. //! <tt>byteCount = 10</tt> means only the first 8 bytes are reversed.
  1534. //! \note ByteReverse uses the number of bytes in the arrays, and not the count
  1535. //! of elements in the arrays.
  1536. template <class T>
  1537. void ByteReverse(T *out, const T *in, size_t byteCount)
  1538. {
  1539. assert(byteCount % sizeof(T) == 0);
  1540. size_t count = byteCount/sizeof(T);
  1541. for (size_t i=0; i<count; i++)
  1542. out[i] = ByteReverse(in[i]);
  1543. }
  1544. //! \brief Reverses bytes in an element among an array of elements depending upon endianess
  1545. //! \tparam T the class or type
  1546. //! \param order the ByteOrder the data is represented
  1547. //! \param out the output array of elements
  1548. //! \param in the input array of elements
  1549. //! \param byteCount the byte count of the arrays
  1550. //! \details Internally, ByteReverse visits each element in the in array
  1551. //! calls ByteReverse on it, and writes the result to out.
  1552. //! \details ByteReverse does not process tail byes, or bytes that are
  1553. //! \a not part of a full element. If T is int (and int is 4 bytes), then
  1554. //! <tt>byteCount = 10</tt> means only the first 8 bytes are reversed.
  1555. //! \note ByteReverse uses the number of bytes in the arrays, and not the count
  1556. //! of elements in the arrays.
  1557. template <class T>
  1558. inline void ConditionalByteReverse(ByteOrder order, T *out, const T *in, size_t byteCount)
  1559. {
  1560. if (!NativeByteOrderIs(order))
  1561. ByteReverse(out, in, byteCount);
  1562. else if (in != out)
  1563. memcpy_s(out, byteCount, in, byteCount);
  1564. }
  1565. template <class T>
  1566. inline void GetUserKey(ByteOrder order, T *out, size_t outlen, const byte *in, size_t inlen)
  1567. {
  1568. const size_t U = sizeof(T);
  1569. assert(inlen <= outlen*U);
  1570. memcpy_s(out, outlen*U, in, inlen);
  1571. memset_z((byte *)out+inlen, 0, outlen*U-inlen);
  1572. ConditionalByteReverse(order, out, out, RoundUpToMultipleOf(inlen, U));
  1573. }
  1574. #ifndef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
  1575. inline byte UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const byte *)
  1576. {
  1577. CRYPTOPP_UNUSED(order);
  1578. return block[0];
  1579. }
  1580. inline word16 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word16 *)
  1581. {
  1582. return (order == BIG_ENDIAN_ORDER)
  1583. ? block[1] | (block[0] << 8)
  1584. : block[0] | (block[1] << 8);
  1585. }
  1586. inline word32 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word32 *)
  1587. {
  1588. return (order == BIG_ENDIAN_ORDER)
  1589. ? word32(block[3]) | (word32(block[2]) << 8) | (word32(block[1]) << 16) | (word32(block[0]) << 24)
  1590. : word32(block[0]) | (word32(block[1]) << 8) | (word32(block[2]) << 16) | (word32(block[3]) << 24);
  1591. }
  1592. inline word64 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word64 *)
  1593. {
  1594. return (order == BIG_ENDIAN_ORDER)
  1595. ?
  1596. (word64(block[7]) |
  1597. (word64(block[6]) << 8) |
  1598. (word64(block[5]) << 16) |
  1599. (word64(block[4]) << 24) |
  1600. (word64(block[3]) << 32) |
  1601. (word64(block[2]) << 40) |
  1602. (word64(block[1]) << 48) |
  1603. (word64(block[0]) << 56))
  1604. :
  1605. (word64(block[0]) |
  1606. (word64(block[1]) << 8) |
  1607. (word64(block[2]) << 16) |
  1608. (word64(block[3]) << 24) |
  1609. (word64(block[4]) << 32) |
  1610. (word64(block[5]) << 40) |
  1611. (word64(block[6]) << 48) |
  1612. (word64(block[7]) << 56));
  1613. }
  1614. inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, byte value, const byte *xorBlock)
  1615. {
  1616. CRYPTOPP_UNUSED(order);
  1617. block[0] = xorBlock ? (value ^ xorBlock[0]) : value;
  1618. }
  1619. inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word16 value, const byte *xorBlock)
  1620. {
  1621. if (order == BIG_ENDIAN_ORDER)
  1622. {
  1623. if (xorBlock)
  1624. {
  1625. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  1626. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  1627. }
  1628. else
  1629. {
  1630. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  1631. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  1632. }
  1633. }
  1634. else
  1635. {
  1636. if (xorBlock)
  1637. {
  1638. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  1639. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  1640. }
  1641. else
  1642. {
  1643. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  1644. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  1645. }
  1646. }
  1647. }
  1648. inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word32 value, const byte *xorBlock)
  1649. {
  1650. if (order == BIG_ENDIAN_ORDER)
  1651. {
  1652. if (xorBlock)
  1653. {
  1654. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  1655. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  1656. block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  1657. block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  1658. }
  1659. else
  1660. {
  1661. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  1662. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  1663. block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  1664. block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  1665. }
  1666. }
  1667. else
  1668. {
  1669. if (xorBlock)
  1670. {
  1671. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  1672. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  1673. block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  1674. block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  1675. }
  1676. else
  1677. {
  1678. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  1679. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  1680. block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  1681. block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  1682. }
  1683. }
  1684. }
  1685. inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word64 value, const byte *xorBlock)
  1686. {
  1687. if (order == BIG_ENDIAN_ORDER)
  1688. {
  1689. if (xorBlock)
  1690. {
  1691. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
  1692. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
  1693. block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
  1694. block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
  1695. block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  1696. block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  1697. block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  1698. block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  1699. }
  1700. else
  1701. {
  1702. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
  1703. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
  1704. block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
  1705. block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
  1706. block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  1707. block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  1708. block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  1709. block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  1710. }
  1711. }
  1712. else
  1713. {
  1714. if (xorBlock)
  1715. {
  1716. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  1717. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  1718. block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  1719. block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  1720. block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
  1721. block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
  1722. block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
  1723. block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
  1724. }
  1725. else
  1726. {
  1727. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  1728. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  1729. block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  1730. block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  1731. block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
  1732. block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
  1733. block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
  1734. block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
  1735. }
  1736. }
  1737. }
  1738. #endif // #ifndef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
  1739. template <class T>
  1740. inline T GetWord(bool assumeAligned, ByteOrder order, const byte *block)
  1741. {
  1742. //#ifndef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
  1743. // if (!assumeAligned)
  1744. // return UnalignedGetWordNonTemplate(order, block, (T*)NULL);
  1745. // assert(IsAligned<T>(block));
  1746. //#endif
  1747. // return ConditionalByteReverse(order, *reinterpret_cast<const T *>(block));
  1748. CRYPTOPP_UNUSED(assumeAligned);
  1749. #ifdef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
  1750. return ConditionalByteReverse(order, *reinterpret_cast<const T *>(block));
  1751. #else
  1752. T temp;
  1753. memcpy(&temp, block, sizeof(T));
  1754. return ConditionalByteReverse(order, temp);
  1755. #endif
  1756. }
  1757. template <class T>
  1758. inline void GetWord(bool assumeAligned, ByteOrder order, T &result, const byte *block)
  1759. {
  1760. result = GetWord<T>(assumeAligned, order, block);
  1761. }
  1762. template <class T>
  1763. inline void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock = NULL)
  1764. {
  1765. //#ifndef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
  1766. // if (!assumeAligned)
  1767. // return UnalignedbyteNonTemplate(order, block, value, xorBlock);
  1768. // assert(IsAligned<T>(block));
  1769. // assert(IsAligned<T>(xorBlock));
  1770. //#endif
  1771. // *reinterpret_cast<T *>(block) = ConditionalByteReverse(order, value) ^ (xorBlock ? *reinterpret_cast<const T *>(xorBlock) : 0);
  1772. CRYPTOPP_UNUSED(assumeAligned);
  1773. #ifdef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
  1774. *reinterpret_cast<T *>(block) = ConditionalByteReverse(order, value) ^ (xorBlock ? *reinterpret_cast<const T *>(xorBlock) : 0);
  1775. #else
  1776. T t1, t2 = 0;
  1777. t1 = ConditionalByteReverse(order, value);
  1778. if (xorBlock) memcpy(&t2, xorBlock, sizeof(T));
  1779. memmove(block, &(t1 ^= t2), sizeof(T));
  1780. #endif
  1781. }
  1782. template <class T, class B, bool A=false>
  1783. class GetBlock
  1784. {
  1785. public:
  1786. GetBlock(const void *block)
  1787. : m_block((const byte *)block) {}
  1788. template <class U>
  1789. inline GetBlock<T, B, A> & operator()(U &x)
  1790. {
  1791. CRYPTOPP_COMPILE_ASSERT(sizeof(U) >= sizeof(T));
  1792. x = GetWord<T>(A, B::ToEnum(), m_block);
  1793. m_block += sizeof(T);
  1794. return *this;
  1795. }
  1796. private:
  1797. const byte *m_block;
  1798. };
  1799. template <class T, class B, bool A=false>
  1800. class PutBlock
  1801. {
  1802. public:
  1803. PutBlock(const void *xorBlock, void *block)
  1804. : m_xorBlock((const byte *)xorBlock), m_block((byte *)block) {}
  1805. template <class U>
  1806. inline PutBlock<T, B, A> & operator()(U x)
  1807. {
  1808. PutWord(A, B::ToEnum(), m_block, (T)x, m_xorBlock);
  1809. m_block += sizeof(T);
  1810. if (m_xorBlock)
  1811. m_xorBlock += sizeof(T);
  1812. return *this;
  1813. }
  1814. private:
  1815. const byte *m_xorBlock;
  1816. byte *m_block;
  1817. };
  1818. template <class T, class B, bool GA=false, bool PA=false>
  1819. struct BlockGetAndPut
  1820. {
  1821. // function needed because of C++ grammatical ambiguity between expression-statements and declarations
  1822. static inline GetBlock<T, B, GA> Get(const void *block) {return GetBlock<T, B, GA>(block);}
  1823. typedef PutBlock<T, B, PA> Put;
  1824. };
  1825. template <class T>
  1826. std::string WordToString(T value, ByteOrder order = BIG_ENDIAN_ORDER)
  1827. {
  1828. if (!NativeByteOrderIs(order))
  1829. value = ByteReverse(value);
  1830. return std::string((char *)&value, sizeof(value));
  1831. }
  1832. template <class T>
  1833. T StringToWord(const std::string &str, ByteOrder order = BIG_ENDIAN_ORDER)
  1834. {
  1835. T value = 0;
  1836. memcpy_s(&value, sizeof(value), str.data(), UnsignedMin(str.size(), sizeof(value)));
  1837. return NativeByteOrderIs(order) ? value : ByteReverse(value);
  1838. }
  1839. // ************** help remove warning on g++ ***************
  1840. template <bool overflow> struct SafeShifter;
  1841. template<> struct SafeShifter<true>
  1842. {
  1843. template <class T>
  1844. static inline T RightShift(T value, unsigned int bits)
  1845. {
  1846. CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits);
  1847. return 0;
  1848. }
  1849. template <class T>
  1850. static inline T LeftShift(T value, unsigned int bits)
  1851. {
  1852. CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits);
  1853. return 0;
  1854. }
  1855. };
  1856. template<> struct SafeShifter<false>
  1857. {
  1858. template <class T>
  1859. static inline T RightShift(T value, unsigned int bits)
  1860. {
  1861. return value >> bits;
  1862. }
  1863. template <class T>
  1864. static inline T LeftShift(T value, unsigned int bits)
  1865. {
  1866. return value << bits;
  1867. }
  1868. };
  1869. template <unsigned int bits, class T>
  1870. inline T SafeRightShift(T value)
  1871. {
  1872. return SafeShifter<(bits>=(8*sizeof(T)))>::RightShift(value, bits);
  1873. }
  1874. template <unsigned int bits, class T>
  1875. inline T SafeLeftShift(T value)
  1876. {
  1877. return SafeShifter<(bits>=(8*sizeof(T)))>::LeftShift(value, bits);
  1878. }
  1879. // ************** use one buffer for multiple data members ***************
  1880. #define CRYPTOPP_BLOCK_1(n, t, s) t* m_##n() {return (t *)(m_aggregate+0);} size_t SS1() {return sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  1881. #define CRYPTOPP_BLOCK_2(n, t, s) t* m_##n() {return (t *)(m_aggregate+SS1());} size_t SS2() {return SS1()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  1882. #define CRYPTOPP_BLOCK_3(n, t, s) t* m_##n() {return (t *)(m_aggregate+SS2());} size_t SS3() {return SS2()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  1883. #define CRYPTOPP_BLOCK_4(n, t, s) t* m_##n() {return (t *)(m_aggregate+SS3());} size_t SS4() {return SS3()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  1884. #define CRYPTOPP_BLOCK_5(n, t, s) t* m_##n() {return (t *)(m_aggregate+SS4());} size_t SS5() {return SS4()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  1885. #define CRYPTOPP_BLOCK_6(n, t, s) t* m_##n() {return (t *)(m_aggregate+SS5());} size_t SS6() {return SS5()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  1886. #define CRYPTOPP_BLOCK_7(n, t, s) t* m_##n() {return (t *)(m_aggregate+SS6());} size_t SS7() {return SS6()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  1887. #define CRYPTOPP_BLOCK_8(n, t, s) t* m_##n() {return (t *)(m_aggregate+SS7());} size_t SS8() {return SS7()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  1888. #define CRYPTOPP_BLOCKS_END(i) size_t SST() {return SS##i();} void AllocateBlocks() {m_aggregate.New(SST());} AlignedSecByteBlock m_aggregate;
  1889. NAMESPACE_END
  1890. #if CRYPTOPP_MSC_VERSION
  1891. # pragma warning(pop)
  1892. #endif
  1893. #endif