Crypto++  6.1
Free C++ class library of cryptographic schemes
misc.h
Go to the documentation of this file.
1 // misc.h - originally written and placed in the public domain by Wei Dai
2 
3 /// \file misc.h
4 /// \brief Utility functions for the Crypto++ library.
5 
6 #ifndef CRYPTOPP_MISC_H
7 #define CRYPTOPP_MISC_H
8 
9 #include "config.h"
10 
11 #if !defined(CRYPTOPP_DOXYGEN_PROCESSING)
12 
13 #if (CRYPTOPP_MSC_VERSION)
14 # pragma warning(push)
15 # pragma warning(disable: 4146 4514)
16 # if (CRYPTOPP_MSC_VERSION >= 1400)
17 # pragma warning(disable: 6326)
18 # endif
19 #endif
20 
21 // Issue 340
22 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
23 # pragma GCC diagnostic push
24 # pragma GCC diagnostic ignored "-Wconversion"
25 # pragma GCC diagnostic ignored "-Wsign-conversion"
26 #endif
27 
28 #include "cryptlib.h"
29 #include "stdcpp.h"
30 #include "smartptr.h"
31 
32 #ifdef _MSC_VER
33  #if _MSC_VER >= 1400
34  // VC2005 workaround: disable declarations that conflict with winnt.h
35  #define _interlockedbittestandset CRYPTOPP_DISABLED_INTRINSIC_1
36  #define _interlockedbittestandreset CRYPTOPP_DISABLED_INTRINSIC_2
37  #define _interlockedbittestandset64 CRYPTOPP_DISABLED_INTRINSIC_3
38  #define _interlockedbittestandreset64 CRYPTOPP_DISABLED_INTRINSIC_4
39  #include <intrin.h>
40  #undef _interlockedbittestandset
41  #undef _interlockedbittestandreset
42  #undef _interlockedbittestandset64
43  #undef _interlockedbittestandreset64
44  #define CRYPTOPP_FAST_ROTATE(x) 1
45  #elif _MSC_VER >= 1300
46  #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32 | (x) == 64)
47  #else
48  #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32)
49  #endif
50 #elif (defined(__MWERKS__) && TARGET_CPU_PPC) || \
51  (defined(__GNUC__) && (defined(_ARCH_PWR2) || defined(_ARCH_PWR) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || defined(_ARCH_COM)))
52  #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32)
53 #elif defined(__GNUC__) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86) // depend on GCC's peephole optimization to generate rotate instructions
54  #define CRYPTOPP_FAST_ROTATE(x) 1
55 #else
56  #define CRYPTOPP_FAST_ROTATE(x) 0
57 #endif
58 
59 #ifdef __BORLANDC__
60 #include <mem.h>
61 #include <stdlib.h>
62 #endif
63 
64 #if defined(__GNUC__) && defined(__linux__)
65 #define CRYPTOPP_BYTESWAP_AVAILABLE
66 #include <byteswap.h>
67 #endif
68 
69 #if defined(__BMI__)
70 # include <x86intrin.h>
71 #endif // GCC and BMI
72 
73 #endif // CRYPTOPP_DOXYGEN_PROCESSING
74 
75 #if CRYPTOPP_DOXYGEN_PROCESSING
76 /// \brief The maximum value of a machine word
77 /// \details SIZE_MAX provides the maximum value of a machine word. The value is
78 /// 0xffffffff on 32-bit machines, and 0xffffffffffffffff on 64-bit machines.
79 /// Internally, SIZE_MAX is defined as __SIZE_MAX__ if __SIZE_MAX__ is defined. If not
80 /// defined, then SIZE_T_MAX is tried. If neither __SIZE_MAX__ nor SIZE_T_MAX is
81 /// is defined, the library uses std::numeric_limits<size_t>::max(). The library
82 /// prefers __SIZE_MAX__ because its a constexpr that is optimized well
83 /// by all compilers. std::numeric_limits<size_t>::max() is not a constexpr,
84 /// and it is not always optimized well.
85 # define SIZE_MAX ...
86 #else
87 // Its amazing portability problems still plague this simple concept in 2015.
88 // http://stackoverflow.com/questions/30472731/which-c-standard-header-defines-size-max
89 // Avoid NOMINMAX macro on Windows. http://support.microsoft.com/en-us/kb/143208
90 #ifndef SIZE_MAX
91 # if defined(__SIZE_MAX__) && (__SIZE_MAX__ > 0)
92 # define SIZE_MAX __SIZE_MAX__
93 # elif defined(SIZE_T_MAX) && (SIZE_T_MAX > 0)
94 # define SIZE_MAX SIZE_T_MAX
95 # elif defined(__SIZE_TYPE__)
96 # define SIZE_MAX (~(__SIZE_TYPE__)0)
97 # else
98 # define SIZE_MAX ((std::numeric_limits<size_t>::max)())
99 # endif
100 #endif
101 
102 #endif // CRYPTOPP_DOXYGEN_PROCESSING
103 
104 // NumericLimitsMin and NumericLimitsMax added for word128 types,
105 // see http://github.com/weidai11/cryptopp/issues/364
106 ANONYMOUS_NAMESPACE_BEGIN
107 template<class T>
108 T NumericLimitsMin()
109 {
110  CRYPTOPP_ASSERT(std::numeric_limits<T>::is_specialized);
111  return (std::numeric_limits<T>::min)();
112 };
113 template<class T>
114 T NumericLimitsMax()
115 {
116  CRYPTOPP_ASSERT(std::numeric_limits<T>::is_specialized);
117  return (std::numeric_limits<T>::max)();
118 };
119 #if defined(CRYPTOPP_WORD128_AVAILABLE)
120 template<>
121 CryptoPP::word128 NumericLimitsMin()
122 {
123  return 0;
124 }
125 template<>
126 CryptoPP::word128 NumericLimitsMax()
127 {
128  return (((CryptoPP::word128)W64LIT(0xffffffffffffffff)) << 64U) | (CryptoPP::word128)W64LIT(0xffffffffffffffff);
129 }
130 #endif
131 ANONYMOUS_NAMESPACE_END
132 
133 NAMESPACE_BEGIN(CryptoPP)
134 
135 // Forward declaration for IntToString specialization
136 class Integer;
137 
138 // ************** compile-time assertion ***************
139 
140 #if CRYPTOPP_DOXYGEN_PROCESSING
141 /// \brief Compile time assertion
142 /// \param expr the expression to evaluate
143 /// \details Asserts the expression expr though a dummy struct.
144 #define CRYPTOPP_COMPILE_ASSERT(expr) { ... }
145 #else // CRYPTOPP_DOXYGEN_PROCESSING
146 template <bool b>
147 struct CompileAssert
148 {
149  static char dummy[2*b-1];
150 };
151 
152 #define CRYPTOPP_COMPILE_ASSERT(assertion) CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, __LINE__)
153 #if defined(CRYPTOPP_EXPORTS) || defined(CRYPTOPP_IMPORTS)
154 #define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance)
155 #else
156 # if defined(__GNUC__)
157 # define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \
158  static CompileAssert<(assertion)> \
159  CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance) __attribute__ ((unused))
160 # else
161 # define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \
162  static CompileAssert<(assertion)> \
163  CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance)
164 # endif // __GNUC__
165 #endif
166 #define CRYPTOPP_ASSERT_JOIN(X, Y) CRYPTOPP_DO_ASSERT_JOIN(X, Y)
167 #define CRYPTOPP_DO_ASSERT_JOIN(X, Y) X##Y
168 
169 #endif // CRYPTOPP_DOXYGEN_PROCESSING
170 
171 // ************** count elements in an array ***************
172 
173 #if CRYPTOPP_DOXYGEN_PROCESSING
174 /// \brief Counts elements in an array
175 /// \param arr an array of elements
176 /// \details COUNTOF counts elements in an array. On Windows COUNTOF(x) is defined
177 /// to <tt>_countof(x)</tt> to ensure correct results for pointers.
178 /// \note COUNTOF does not produce correct results with pointers, and an array must be used.
179 /// <tt>sizeof(x)/sizeof(x[0])</tt> suffers the same problem. The risk is eliminated by using
180 /// <tt>_countof(x)</tt> on Windows. Windows will provide the immunity for other platforms.
181 # define COUNTOF(arr)
182 #else
183 // VS2005 added _countof
184 #ifndef COUNTOF
185 # if defined(_MSC_VER) && (_MSC_VER >= 1400)
186 # define COUNTOF(x) _countof(x)
187 # else
188 # define COUNTOF(x) (sizeof(x)/sizeof(x[0]))
189 # endif
190 #endif // COUNTOF
191 #endif // CRYPTOPP_DOXYGEN_PROCESSING
192 
193 // ************** misc classes ***************
194 
195 /// \brief An Empty class
196 /// \details The Empty class can be used as a template parameter <tt>BASE</tt> when no base class exists.
197 class CRYPTOPP_DLL Empty
198 {
199 };
200 
201 #if !defined(CRYPTOPP_DOXYGEN_PROCESSING)
202 template <class BASE1, class BASE2>
203 class CRYPTOPP_NO_VTABLE TwoBases : public BASE1, public BASE2
204 {
205 };
206 
207 template <class BASE1, class BASE2, class BASE3>
208 class CRYPTOPP_NO_VTABLE ThreeBases : public BASE1, public BASE2, public BASE3
209 {
210 };
211 #endif // CRYPTOPP_DOXYGEN_PROCESSING
212 
213 /// \tparam T class or type
214 /// \brief Uses encapsulation to hide an object in derived classes
215 /// \details The object T is declared as protected.
216 template <class T>
218 {
219 protected:
220  T m_object;
221 };
222 
223 /// \brief Ensures an object is not copyable
224 /// \details NotCopyable ensures an object is not copyable by making the
225 /// copy constructor and assignment operator private. Deleters are not
226 /// used under C++11.
227 /// \sa Clonable class
229 {
230 public:
231  NotCopyable() {}
232 private:
233  NotCopyable(const NotCopyable &);
234  void operator=(const NotCopyable &);
235 };
236 
237 /// \brief An object factory function
238 /// \tparam T class or type
239 /// \details NewObject overloads operator()().
240 template <class T>
241 struct NewObject
242 {
243  T* operator()() const {return new T;}
244 };
245 
246 #if CRYPTOPP_DOXYGEN_PROCESSING
247 /// \brief A memory barrier
248 /// \details MEMORY_BARRIER attempts to ensure reads and writes are completed
249 /// in the absence of a language synchronization point. It is used by the
250 /// Singleton class if the compiler supports it. The barrier is provided at the
251 /// customary places in a double-checked initialization.
252 /// \details Internally, MEMORY_BARRIER uses <tt>std::atomic_thread_fence</tt> if
253 /// C++11 atomics are available. Otherwise, <tt>intrinsic(_ReadWriteBarrier)</tt>,
254 /// <tt>_ReadWriteBarrier()</tt> or <tt>__asm__("" ::: "memory")</tt> is used.
255 #define MEMORY_BARRIER ...
256 #else
257 #if defined(CRYPTOPP_CXX11_ATOMICS)
258 # define MEMORY_BARRIER() std::atomic_thread_fence(std::memory_order_acq_rel)
259 #elif (_MSC_VER >= 1400)
260 # pragma intrinsic(_ReadWriteBarrier)
261 # define MEMORY_BARRIER() _ReadWriteBarrier()
262 #elif defined(__INTEL_COMPILER)
263 # define MEMORY_BARRIER() __memory_barrier()
264 #elif defined(__GNUC__) || defined(__clang__)
265 # define MEMORY_BARRIER() __asm__ __volatile__ ("" ::: "memory")
266 #else
267 # define MEMORY_BARRIER()
268 #endif
269 #endif // CRYPTOPP_DOXYGEN_PROCESSING
270 
271 /// \brief Restricts the instantiation of a class to one static object without locks
272 /// \tparam T the class or type
273 /// \tparam F the object factory for T
274 /// \tparam instance an instance counter for the class object
275 /// \details This class safely initializes a static object in a multithreaded environment. For C++03
276 /// and below it will do so without using locks for portability. If two threads call Ref() at the same
277 /// time, they may get back different references, and one object may end up being memory leaked. This
278 /// is by design and it avoids a subltle initialization problem ina multithreaded environment with thread
279 /// local storage on early Windows platforms, like Windows XP and Windows 2003.
280 /// \details For C++11 and above, a standard double-checked locking pattern with thread fences
281 /// are used. The locks and fences are standard and do not hinder portability.
282 /// \details Microsoft's C++11 implementation provides the necessary primitive support on Windows Vista and
283 /// above when using Visual Studio 2015 (<tt>cl.exe</tt> version 19.00). If C++11 is desired, you should
284 /// set <tt>WINVER</tt> or <tt>_WIN32_WINNT</tt> to 0x600 (or above), and compile with Visual Studio 2015.
285 /// \sa <A HREF="http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/">Double-Checked Locking
286 /// is Fixed In C++11</A>, <A HREF="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm">Dynamic
287 /// Initialization and Destruction with Concurrency</A> and
288 /// <A HREF="http://msdn.microsoft.com/en-us/library/6yh4a9k1.aspx">Thread Local Storage (TLS)</A> on MSDN.
289 /// \since Crypto++ 5.2
290 template <class T, class F = NewObject<T>, int instance=0>
292 {
293 public:
294  Singleton(F objectFactory = F()) : m_objectFactory(objectFactory) {}
295 
296  // prevent this function from being inlined
297  CRYPTOPP_NOINLINE const T & Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const;
298 
299 private:
300  F m_objectFactory;
301 };
302 
303 /// \brief Return a reference to the inner Singleton object
304 /// \tparam T the class or type
305 /// \tparam F the object factory for T
306 /// \tparam instance an instance counter for the class object
307 /// \details Ref() is used to create the object using the object factory. The
308 /// object is only created once with the limitations discussed in the class documentation.
309 /// \sa <A HREF="http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/">Double-Checked Locking is Fixed In C++11</A>
310 /// \since Crypto++ 5.2
311 template <class T, class F, int instance>
312  const T & Singleton<T, F, instance>::Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const
313 {
314 #if defined(CRYPTOPP_CXX11_ATOMICS) && defined(CRYPTOPP_CXX11_SYNCHRONIZATION) && defined(CRYPTOPP_CXX11_DYNAMIC_INIT)
315  static std::mutex s_mutex;
316  static std::atomic<T*> s_pObject;
317 
318  T *p = s_pObject.load(std::memory_order_relaxed);
319  std::atomic_thread_fence(std::memory_order_acquire);
320 
321  if (p)
322  return *p;
323 
324  std::lock_guard<std::mutex> lock(s_mutex);
325  p = s_pObject.load(std::memory_order_relaxed);
326  std::atomic_thread_fence(std::memory_order_acquire);
327 
328  if (p)
329  return *p;
330 
331  T *newObject = m_objectFactory();
332  s_pObject.store(newObject, std::memory_order_relaxed);
333  std::atomic_thread_fence(std::memory_order_release);
334 
335  return *newObject;
336 #else
337  static volatile simple_ptr<T> s_pObject;
338  T *p = s_pObject.m_p;
339  MEMORY_BARRIER();
340 
341  if (p)
342  return *p;
343 
344  T *newObject = m_objectFactory();
345  p = s_pObject.m_p;
346  MEMORY_BARRIER();
347 
348  if (p)
349  {
350  delete newObject;
351  return *p;
352  }
353 
354  s_pObject.m_p = newObject;
355  MEMORY_BARRIER();
356 
357  return *newObject;
358 #endif
359 }
360 
361 // ************** misc functions ***************
362 
363 #if (!__STDC_WANT_SECURE_LIB__ && !defined(_MEMORY_S_DEFINED)) || defined(CRYPTOPP_WANT_SECURE_LIB)
364 
365 /// \brief Bounds checking replacement for memcpy()
366 /// \param dest pointer to the desination memory block
367 /// \param sizeInBytes size of the desination memory block, in bytes
368 /// \param src pointer to the source memory block
369 /// \param count the number of bytes to copy
370 /// \throws InvalidArgument
371 /// \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially
372 /// unsafe functions like memcpy(), strcpy() and memmove(). However,
373 /// not all standard libraries provides them, like Glibc. The library's
374 /// memcpy_s() is a near-drop in replacement. Its only a near-replacement
375 /// because the library's version throws an InvalidArgument on a bounds violation.
376 /// \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__.
377 /// If __STDC_WANT_SECURE_LIB__ is not defined or defined to 0, then the library
378 /// makes memcpy_s() and memmove_s() available. The library will also optionally
379 /// make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined.
380 /// <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default.
381 /// \details memcpy_s() will assert the pointers src and dest are not NULL
382 /// in debug builds. Passing NULL for either pointer is undefined behavior.
383 inline void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
384 {
385  // Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55
386 
387  // Pointers must be valid; otherwise undefined behavior
388  CRYPTOPP_ASSERT(dest != NULLPTR); CRYPTOPP_ASSERT(src != NULLPTR);
389  // Restricted pointers. We want to check ranges, but it is not clear how to do it.
390  CRYPTOPP_ASSERT(src != dest);
391  // Destination buffer must be large enough to satsify request
392  CRYPTOPP_ASSERT(sizeInBytes >= count);
393 
394  if (count > sizeInBytes)
395  throw InvalidArgument("memcpy_s: buffer overflow");
396 
397 #if CRYPTOPP_MSC_VERSION
398 # pragma warning(push)
399 # pragma warning(disable: 4996)
400 # if (CRYPTOPP_MSC_VERSION >= 1400)
401 # pragma warning(disable: 6386)
402 # endif
403 #endif
404  memcpy(dest, src, count);
405 #if CRYPTOPP_MSC_VERSION
406 # pragma warning(pop)
407 #endif
408 }
409 
410 /// \brief Bounds checking replacement for memmove()
411 /// \param dest pointer to the desination memory block
412 /// \param sizeInBytes size of the desination memory block, in bytes
413 /// \param src pointer to the source memory block
414 /// \param count the number of bytes to copy
415 /// \throws InvalidArgument
416 /// \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially
417 /// unsafe functions like memcpy(), strcpy() and memmove(). However,
418 /// not all standard libraries provides them, like Glibc. The library's
419 /// memmove_s() is a near-drop in replacement. Its only a near-replacement
420 /// because the library's version throws an InvalidArgument on a bounds violation.
421 /// \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__.
422 /// If __STDC_WANT_SECURE_LIB__ is not defined or defined to 0, then the library
423 /// makes memcpy_s() and memmove_s() available. The library will also optionally
424 /// make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined.
425 /// <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default.
426 /// \details memmove_s() will assert the pointers src and dest are not NULL
427 /// in debug builds. Passing NULL for either pointer is undefined behavior.
428 inline void memmove_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
429 {
430  // Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55
431 
432  // Pointers must be valid; otherwise undefined behavior
433  CRYPTOPP_ASSERT(dest != NULLPTR); CRYPTOPP_ASSERT(src != NULLPTR);
434  // Destination buffer must be large enough to satsify request
435  CRYPTOPP_ASSERT(sizeInBytes >= count);
436 
437  if (count > sizeInBytes)
438  throw InvalidArgument("memmove_s: buffer overflow");
439 
440 #if CRYPTOPP_MSC_VERSION
441 # pragma warning(push)
442 # pragma warning(disable: 4996)
443 # if (CRYPTOPP_MSC_VERSION >= 1400)
444 # pragma warning(disable: 6386)
445 # endif
446 #endif
447  memmove(dest, src, count);
448 #if CRYPTOPP_MSC_VERSION
449 # pragma warning(pop)
450 #endif
451 }
452 
453 #if __BORLANDC__ >= 0x620
454 // C++Builder 2010 workaround: can't use std::memcpy_s because it doesn't allow 0 lengths
455 # define memcpy_s CryptoPP::memcpy_s
456 # define memmove_s CryptoPP::memmove_s
457 #endif
458 
459 #endif // __STDC_WANT_SECURE_LIB__
460 
461 /// \brief Swaps two variables which are arrays
462 /// \tparam T class or type
463 /// \param a the first value
464 /// \param b the second value
465 /// \details C++03 does not provide support for <tt>std::swap(__m128i a, __m128i b)</tt>
466 /// because <tt>__m128i</tt> is an <tt>unsigned long long[2]</tt>. Most compilers
467 /// support it out of the box, but Sun Studio C++ compilers 12.2 and 12.3 do not.
468 /// \sa <A HREF="http://stackoverflow.com/q/38417413">How to swap two __m128i variables
469 /// in C++03 given its an opaque type and an array?</A> on Stack Overflow.
470 template <class T>
471 inline void vec_swap(T& a, T& b)
472 {
473  // __m128i is an unsigned long long[2], and support for swapping it was
474  // not added until C++11. SunCC 12.1 - 12.3 fail to consume the swap; while
475  // SunCC 12.4 consumes it without -std=c++11.
476 #if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x5120)
477  T t;
478  t=a, a=b, b=t;
479 #else
480  std::swap(a, b);
481 #endif
482 }
483 
484 /// \brief Memory block initializer and eraser that attempts to survive optimizations
485 /// \param ptr pointer to the memory block being written
486 /// \param value the integer value to write for each byte
487 /// \param num the size of the source memory block, in bytes
488 /// \details Internally the function calls memset with the value value, and receives the
489 /// return value from memset as a <tt>volatile</tt> pointer.
490 inline void * memset_z(void *ptr, int value, size_t num)
491 {
492 // avoid extranous warning on GCC 4.3.2 Ubuntu 8.10
493 #if CRYPTOPP_GCC_VERSION >= 30001
494  if (__builtin_constant_p(num) && num==0)
495  return ptr;
496 #endif
497  volatile void* x = memset(ptr, value, num);
498  return const_cast<void*>(x);
499 }
500 
501 /// \brief Replacement function for std::min
502 /// \tparam T class or type
503 /// \param a the first value
504 /// \param b the second value
505 /// \returns the minimum value based on a comparison of <tt>b < a</tt> using <tt>operator<</tt>
506 /// \details STDMIN was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0
507 template <class T> inline const T& STDMIN(const T& a, const T& b)
508 {
509  return b < a ? b : a;
510 }
511 
512 /// \brief Replacement function for std::max
513 /// \tparam T class or type
514 /// \param a the first value
515 /// \param b the second value
516 /// \returns the minimum value based on a comparison of <tt>a < b</tt> using <tt>operator<</tt>
517 /// \details STDMAX was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0
518 template <class T> inline const T& STDMAX(const T& a, const T& b)
519 {
520  return a < b ? b : a;
521 }
522 
523 #if CRYPTOPP_MSC_VERSION
524 # pragma warning(push)
525 # pragma warning(disable: 4389)
526 #endif
527 
528 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
529 # pragma GCC diagnostic push
530 # pragma GCC diagnostic ignored "-Wsign-compare"
531 # pragma GCC diagnostic ignored "-Wstrict-overflow"
532 # if (CRYPTOPP_LLVM_CLANG_VERSION >= 20800) || (CRYPTOPP_APPLE_CLANG_VERSION >= 30000)
533 # pragma GCC diagnostic ignored "-Wtautological-compare"
534 # elif (CRYPTOPP_GCC_VERSION >= 40300)
535 # pragma GCC diagnostic ignored "-Wtype-limits"
536 # endif
537 #endif
538 
539 /// \brief Safe comparison of values that could be neagtive and incorrectly promoted
540 /// \tparam T1 class or type
541 /// \tparam T2 class or type
542 /// \param a the first value
543 /// \param b the second value
544 /// \returns the minimum value based on a comparison a and b using <tt>operator&lt;</tt>.
545 /// \details The comparison <tt>b < a</tt> is performed and the value returned is a's type T1.
546 template <class T1, class T2> inline const T1 UnsignedMin(const T1& a, const T2& b)
547 {
548  CRYPTOPP_COMPILE_ASSERT((sizeof(T1)<=sizeof(T2) && T2(-1)>0) || (sizeof(T1)>sizeof(T2) && T1(-1)>0));
549  if (sizeof(T1)<=sizeof(T2))
550  return b < (T2)a ? (T1)b : a;
551  else
552  return (T1)b < a ? (T1)b : a;
553 }
554 
555 /// \brief Tests whether a conversion from -> to is safe to perform
556 /// \tparam T1 class or type
557 /// \tparam T2 class or type
558 /// \param from the first value
559 /// \param to the second value
560 /// \returns true if its safe to convert from into to, false otherwise.
561 template <class T1, class T2>
562 inline bool SafeConvert(T1 from, T2 &to)
563 {
564  to = (T2)from;
565  if (from != to || (from > 0) != (to > 0))
566  return false;
567  return true;
568 }
569 
570 /// \brief Converts a value to a string
571 /// \tparam T class or type
572 /// \param value the value to convert
573 /// \param base the base to use during the conversion
574 /// \returns the string representation of value in base.
575 template <class T>
576 std::string IntToString(T value, unsigned int base = 10)
577 {
578  // Hack... set the high bit for uppercase.
579  static const unsigned int HIGH_BIT = (1U << 31);
580  const char CH = !!(base & HIGH_BIT) ? 'A' : 'a';
581  base &= ~HIGH_BIT;
582 
583  CRYPTOPP_ASSERT(base >= 2);
584  if (value == 0)
585  return "0";
586 
587  bool negate = false;
588  if (value < 0)
589  {
590  negate = true;
591  value = 0-value; // VC .NET does not like -a
592  }
593  std::string result;
594  while (value > 0)
595  {
596  T digit = value % base;
597  result = char((digit < 10 ? '0' : (CH - 10)) + digit) + result;
598  value /= base;
599  }
600  if (negate)
601  result = "-" + result;
602  return result;
603 }
604 
605 /// \brief Converts an unsigned value to a string
606 /// \param value the value to convert
607 /// \param base the base to use during the conversion
608 /// \returns the string representation of value in base.
609 /// \details this template function specialization was added to suppress
610 /// Coverity findings on IntToString() with unsigned types.
611 template <> CRYPTOPP_DLL
612 std::string IntToString<word64>(word64 value, unsigned int base);
613 
614 /// \brief Converts an Integer to a string
615 /// \param value the Integer to convert
616 /// \param base the base to use during the conversion
617 /// \returns the string representation of value in base.
618 /// \details This is a template specialization of IntToString(). Use it
619 /// like IntToString():
620 /// <pre>
621 /// // Print integer in base 10
622 /// Integer n...
623 /// std::string s = IntToString(n, 10);
624 /// </pre>
625 /// \details The string is presented with lowercase letters by default. A
626 /// hack is available to switch to uppercase letters without modifying
627 /// the function signature.
628 /// <pre>
629 /// // Print integer in base 16, uppercase letters
630 /// Integer n...
631 /// const unsigned int UPPER = (1 << 31);
632 /// std::string s = IntToString(n, (UPPER | 16));</pre>
633 template <> CRYPTOPP_DLL
634 std::string IntToString<Integer>(Integer value, unsigned int base);
635 
636 #if CRYPTOPP_MSC_VERSION
637 # pragma warning(pop)
638 #endif
639 
640 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
641 # pragma GCC diagnostic pop
642 #endif
643 
644 #define RETURN_IF_NONZERO(x) size_t returnedValue = x; if (returnedValue) return returnedValue
645 
646 // this version of the macro is fastest on Pentium 3 and Pentium 4 with MSVC 6 SP5 w/ Processor Pack
647 #define GETBYTE(x, y) (unsigned int)byte((x)>>(8*(y)))
648 // these may be faster on other CPUs/compilers
649 // #define GETBYTE(x, y) (unsigned int)(((x)>>(8*(y)))&255)
650 // #define GETBYTE(x, y) (((byte *)&(x))[y])
651 
652 #define CRYPTOPP_GET_BYTE_AS_BYTE(x, y) byte((x)>>(8*(y)))
653 
654 /// \brief Returns the parity of a value
655 /// \tparam T class or type
656 /// \param value the value to provide the parity
657 /// \returns 1 if the number 1-bits in the value is odd, 0 otherwise
658 template <class T>
659 unsigned int Parity(T value)
660 {
661  for (unsigned int i=8*sizeof(value)/2; i>0; i/=2)
662  value ^= value >> i;
663  return (unsigned int)value&1;
664 }
665 
666 /// \brief Returns the number of 8-bit bytes or octets required for a value
667 /// \tparam T class or type
668 /// \param value the value to test
669 /// \returns the minimum number of 8-bit bytes or octets required to represent a value
670 template <class T>
671 unsigned int BytePrecision(const T &value)
672 {
673  if (!value)
674  return 0;
675 
676  unsigned int l=0, h=8*sizeof(value);
677  while (h-l > 8)
678  {
679  unsigned int t = (l+h)/2;
680  if (value >> t)
681  l = t;
682  else
683  h = t;
684  }
685 
686  return h/8;
687 }
688 
689 /// \brief Returns the number of bits required for a value
690 /// \tparam T class or type
691 /// \param value the value to test
692 /// \returns the maximum number of bits required to represent a value.
693 template <class T>
694 unsigned int BitPrecision(const T &value)
695 {
696  if (!value)
697  return 0;
698 
699  unsigned int l=0, h=8*sizeof(value);
700 
701  while (h-l > 1)
702  {
703  unsigned int t = (l+h)/2;
704  if (value >> t)
705  l = t;
706  else
707  h = t;
708  }
709 
710  return h;
711 }
712 
713 /// Determines the number of trailing 0-bits in a value
714 /// \param v the 32-bit value to test
715 /// \returns the number of trailing 0-bits in v, starting at the least significant bit position
716 /// \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least
717 /// significant bit position. The return value is undefined if there are no 1-bits set in the value v.
718 /// \note The function does not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position.
719 inline unsigned int TrailingZeros(word32 v)
720 {
721  // GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors
722  // We don't enable for Microsoft because it requires a runtime check.
723  // http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx
724  CRYPTOPP_ASSERT(v != 0);
725 #if defined(__BMI__)
726  return (unsigned int)_tzcnt_u32(v);
727 #elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400)
728  return (unsigned int)__builtin_ctz(v);
729 #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
730  unsigned long result;
731  _BitScanForward(&result, v);
732  return (unsigned int)result;
733 #else
734  // from http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup
735  static const int MultiplyDeBruijnBitPosition[32] =
736  {
737  0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
738  31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
739  };
740  return MultiplyDeBruijnBitPosition[((word32)((v & -v) * 0x077CB531U)) >> 27];
741 #endif
742 }
743 
744 /// Determines the number of trailing 0-bits in a value
745 /// \param v the 64-bit value to test
746 /// \returns the number of trailing 0-bits in v, starting at the least significant bit position
747 /// \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least
748 /// significant bit position. The return value is undefined if there are no 1-bits set in the value v.
749 /// \note The function does not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position.
750 inline unsigned int TrailingZeros(word64 v)
751 {
752  // GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors
753  // We don't enable for Microsoft because it requires a runtime check.
754  // http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx
755  CRYPTOPP_ASSERT(v != 0);
756 #if defined(__BMI__) && defined(__x86_64__)
757  return (unsigned int)_tzcnt_u64(v);
758 #elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400)
759  return (unsigned int)__builtin_ctzll(v);
760 #elif defined(_MSC_VER) && (_MSC_VER >= 1400) && (defined(_M_X64) || defined(_M_IA64))
761  unsigned long result;
762  _BitScanForward64(&result, v);
763  return (unsigned int)result;
764 #else
765  return word32(v) ? TrailingZeros(word32(v)) : 32 + TrailingZeros(word32(v>>32));
766 #endif
767 }
768 
769 /// \brief Truncates the value to the specified number of bits.
770 /// \tparam T class or type
771 /// \param value the value to truncate or mask
772 /// \param bits the number of bits to truncate or mask
773 /// \returns the value truncated to the specified number of bits, starting at the least
774 /// significant bit position
775 /// \details This function masks the low-order bits of value and returns the result. The
776 /// mask is created with <tt>(1 << bits) - 1</tt>.
777 template <class T>
778 inline T Crop(T value, size_t bits)
779 {
780  if (bits < 8*sizeof(value))
781  return T(value & ((T(1) << bits) - 1));
782  else
783  return value;
784 }
785 
786 /// \brief Returns the number of 8-bit bytes or octets required for the specified number of bits
787 /// \param bitCount the number of bits
788 /// \returns the minimum number of 8-bit bytes or octets required by bitCount
789 /// \details BitsToBytes is effectively a ceiling function based on 8-bit bytes.
790 inline size_t BitsToBytes(size_t bitCount)
791 {
792  return ((bitCount+7)/(8));
793 }
794 
795 /// \brief Returns the number of words required for the specified number of bytes
796 /// \param byteCount the number of bytes
797 /// \returns the minimum number of words required by byteCount
798 /// \details BytesToWords is effectively a ceiling function based on <tt>WORD_SIZE</tt>.
799 /// <tt>WORD_SIZE</tt> is defined in config.h
800 inline size_t BytesToWords(size_t byteCount)
801 {
802  return ((byteCount+WORD_SIZE-1)/WORD_SIZE);
803 }
804 
805 /// \brief Returns the number of words required for the specified number of bits
806 /// \param bitCount the number of bits
807 /// \returns the minimum number of words required by bitCount
808 /// \details BitsToWords is effectively a ceiling function based on <tt>WORD_BITS</tt>.
809 /// <tt>WORD_BITS</tt> is defined in config.h
810 inline size_t BitsToWords(size_t bitCount)
811 {
812  return ((bitCount+WORD_BITS-1)/(WORD_BITS));
813 }
814 
815 /// \brief Returns the number of double words required for the specified number of bits
816 /// \param bitCount the number of bits
817 /// \returns the minimum number of double words required by bitCount
818 /// \details BitsToDwords is effectively a ceiling function based on <tt>2*WORD_BITS</tt>.
819 /// <tt>WORD_BITS</tt> is defined in config.h
820 inline size_t BitsToDwords(size_t bitCount)
821 {
822  return ((bitCount+2*WORD_BITS-1)/(2*WORD_BITS));
823 }
824 
825 /// Performs an XOR of a buffer with a mask
826 /// \param buf the buffer to XOR with the mask
827 /// \param mask the mask to XOR with the buffer
828 /// \param count the size of the buffers, in bytes
829 /// \details The function effectively visits each element in the buffers and performs
830 /// <tt>buf[i] ^= mask[i]</tt>. buf and mask must be of equal size.
831 CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *buf, const byte *mask, size_t count);
832 
833 /// Performs an XOR of an input buffer with a mask and stores the result in an output buffer
834 /// \param output the destination buffer
835 /// \param input the source buffer to XOR with the mask
836 /// \param mask the mask buffer to XOR with the input buffer
837 /// \param count the size of the buffers, in bytes
838 /// \details The function effectively visits each element in the buffers and performs
839 /// <tt>output[i] = input[i] ^ mask[i]</tt>. output, input and mask must be of equal size.
840 CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *output, const byte *input, const byte *mask, size_t count);
841 
842 /// \brief Performs a near constant-time comparison of two equally sized buffers
843 /// \param buf1 the first buffer
844 /// \param buf2 the second buffer
845 /// \param count the size of the buffers, in bytes
846 /// \details The function effectively performs an XOR of the elements in two equally sized buffers
847 /// and retruns a result based on the XOR operation. The function is near constant-time because
848 /// CPU micro-code timings could affect the "constant-ness". Calling code is responsible for
849 /// mitigating timing attacks if the buffers are not equally sized.
850 /// \sa ModPowerOf2
851 CRYPTOPP_DLL bool CRYPTOPP_API VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count);
852 
853 /// \brief Tests whether a value is a power of 2
854 /// \param value the value to test
855 /// \returns true if value is a power of 2, false otherwise
856 /// \details The function creates a mask of <tt>value - 1</tt> and returns the result of
857 /// an AND operation compared to 0. If value is 0 or less than 0, then the function returns false.
858 template <class T>
859 inline bool IsPowerOf2(const T &value)
860 {
861  return value > 0 && (value & (value-1)) == 0;
862 }
863 
864 #if defined(__BMI__)
865 template <>
866 inline bool IsPowerOf2<word32>(const word32 &value)
867 {
868  return value > 0 && _blsr_u32(value) == 0;
869 }
870 
871 # if defined(__x86_64__)
872 template <>
873 inline bool IsPowerOf2<word64>(const word64 &value)
874 {
875  return value > 0 && _blsr_u64(value) == 0;
876 }
877 # endif // __x86_64__
878 #endif // __BMI__
879 
880 /// \brief Performs a saturating subtract clamped at 0
881 /// \tparam T1 class or type
882 /// \tparam T2 class or type
883 /// \param a the minuend
884 /// \param b the subtrahend
885 /// \returns the difference produced by the saturating subtract
886 /// \details Saturating arithmetic restricts results to a fixed range. Results that are less than 0 are clamped at 0.
887 /// \details Use of saturating arithmetic in places can be advantageous because it can
888 /// avoid a branch by using an instruction like a conditional move (<tt>CMOVE</tt>).
889 template <class T1, class T2>
890 inline T1 SaturatingSubtract(const T1 &a, const T2 &b)
891 {
892  // Generated ASM of a typical clamp, http://gcc.gnu.org/ml/gcc-help/2014-10/msg00112.html
893  return T1((a > b) ? (a - b) : 0);
894 }
895 
896 /// \brief Performs a saturating subtract clamped at 1
897 /// \tparam T1 class or type
898 /// \tparam T2 class or type
899 /// \param a the minuend
900 /// \param b the subtrahend
901 /// \returns the difference produced by the saturating subtract
902 /// \details Saturating arithmetic restricts results to a fixed range. Results that are less than
903 /// 1 are clamped at 1.
904 /// \details Use of saturating arithmetic in places can be advantageous because it can
905 /// avoid a branch by using an instruction like a conditional move (<tt>CMOVE</tt>).
906 template <class T1, class T2>
907 inline T1 SaturatingSubtract1(const T1 &a, const T2 &b)
908 {
909  // Generated ASM of a typical clamp, http://gcc.gnu.org/ml/gcc-help/2014-10/msg00112.html
910  return T1((a > b) ? (a - b) : 1);
911 }
912 
913 /// \brief Reduces a value to a power of 2
914 /// \tparam T1 class or type
915 /// \tparam T2 class or type
916 /// \param a the first value
917 /// \param b the second value
918 /// \returns ModPowerOf2() returns <tt>a & (b-1)</tt>. <tt>b</tt> must be a power of 2.
919 /// Use IsPowerOf2() to determine if <tt>b</tt> is a suitable candidate.
920 /// \sa IsPowerOf2
921 template <class T1, class T2>
922 inline T2 ModPowerOf2(const T1 &a, const T2 &b)
923 {
925  // Coverity finding CID 170383 Overflowed return value (INTEGER_OVERFLOW)
926  return T2(a) & SaturatingSubtract(b,1U);
927 }
928 
929 /// \brief Rounds a value down to a multiple of a second value
930 /// \tparam T1 class or type
931 /// \tparam T2 class or type
932 /// \param n the value to reduce
933 /// \param m the value to reduce \n to to a multiple
934 /// \returns the possibly unmodified value \n
935 /// \details RoundDownToMultipleOf is effectively a floor function based on m. The function returns
936 /// the value <tt>n - n\%m</tt>. If n is a multiple of m, then the original value is returned.
937 /// \note <tt>T1</tt> and <tt>T2</tt> should be usigned arithmetic types. If <tt>T1</tt> or
938 /// <tt>T2</tt> is signed, then the value should be non-negative. The library asserts in
939 /// debug builds when practical, but allows you to perform the operation in release builds.
940 template <class T1, class T2>
941 inline T1 RoundDownToMultipleOf(const T1 &n, const T2 &m)
942 {
943  // http://github.com/weidai11/cryptopp/issues/364
944 #if !defined(CRYPTOPP_APPLE_CLANG_VERSION) || (CRYPTOPP_APPLE_CLANG_VERSION >= 80000)
945  CRYPTOPP_ASSERT(std::numeric_limits<T1>::is_integer);
946  CRYPTOPP_ASSERT(std::numeric_limits<T2>::is_integer);
947 #endif
948 
949  CRYPTOPP_ASSERT(!std::numeric_limits<T1>::is_signed || n > 0);
950  CRYPTOPP_ASSERT(!std::numeric_limits<T2>::is_signed || m > 0);
951 
952  if (IsPowerOf2(m))
953  return n - ModPowerOf2(n, m);
954  else
955  return n - n%m;
956 }
957 
958 /// \brief Rounds a value up to a multiple of a second value
959 /// \tparam T1 class or type
960 /// \tparam T2 class or type
961 /// \param n the value to reduce
962 /// \param m the value to reduce \n to to a multiple
963 /// \returns the possibly unmodified value \n
964 /// \details RoundUpToMultipleOf is effectively a ceiling function based on m. The function
965 /// returns the value <tt>n + n\%m</tt>. If n is a multiple of m, then the original value is
966 /// returned. If the value n would overflow, then an InvalidArgument exception is thrown.
967 /// \note <tt>T1</tt> and <tt>T2</tt> should be usigned arithmetic types. If <tt>T1</tt> or
968 /// <tt>T2</tt> is signed, then the value should be non-negative. The library asserts in
969 /// debug builds when practical, but allows you to perform the operation in release builds.
970 template <class T1, class T2>
971 inline T1 RoundUpToMultipleOf(const T1 &n, const T2 &m)
972 {
973  // http://github.com/weidai11/cryptopp/issues/364
974 #if !defined(CRYPTOPP_APPLE_CLANG_VERSION) || (CRYPTOPP_APPLE_CLANG_VERSION >= 80000)
975  CRYPTOPP_ASSERT(std::numeric_limits<T1>::is_integer);
976  CRYPTOPP_ASSERT(std::numeric_limits<T2>::is_integer);
977 #endif
978 
979  CRYPTOPP_ASSERT(!std::numeric_limits<T1>::is_signed || n > 0);
980  CRYPTOPP_ASSERT(!std::numeric_limits<T2>::is_signed || m > 0);
981 
982  if (NumericLimitsMax<T1>() - m + 1 < n)
983  throw InvalidArgument("RoundUpToMultipleOf: integer overflow");
984  return RoundDownToMultipleOf(T1(n+m-1), m);
985 }
986 
987 /// \brief Returns the minimum alignment requirements of a type
988 /// \tparam T class or type
989 /// \returns the minimum alignment requirements of <tt>T</tt>, in bytes
990 /// \details Internally the function calls C++11's <tt>alignof</tt> if available. If not available,
991 /// then the function uses compiler specific extensions such as <tt>__alignof</tt> and
992 /// <tt>_alignof_</tt>. If an extension is not available, then the function uses
993 /// <tt>__BIGGEST_ALIGNMENT__</tt> if <tt>__BIGGEST_ALIGNMENT__</tt> is smaller than <tt>sizeof(T)</tt>.
994 /// <tt>sizeof(T)</tt> is used if all others are not available.
995 /// In <em>all</em> cases, if <tt>CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS</tt> is defined, then the
996 /// function returns 1.
997 template <class T>
998 inline unsigned int GetAlignmentOf()
999 {
1000 // GCC 4.6 (circa 2008) and above aggressively uses vectorization.
1001 #if defined(CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS)
1002  if (sizeof(T) < 16)
1003  return 1;
1004 #endif
1005 
1006 #if defined(CRYPTOPP_CXX11_ALIGNOF)
1007  return alignof(T);
1008 #elif (_MSC_VER >= 1300)
1009  return __alignof(T);
1010 #elif defined(__GNUC__)
1011  return __alignof__(T);
1012 #elif CRYPTOPP_BOOL_SLOW_WORD64
1013  return UnsignedMin(4U, sizeof(T));
1014 #else
1015 # if __BIGGEST_ALIGNMENT__
1016  if (__BIGGEST_ALIGNMENT__ < sizeof(T))
1017  return __BIGGEST_ALIGNMENT__;
1018  else
1019 # endif
1020  return sizeof(T);
1021 #endif
1022 }
1023 
1024 /// \brief Determines whether ptr is aligned to a minimum value
1025 /// \param ptr the pointer being checked for alignment
1026 /// \param alignment the alignment value to test the pointer against
1027 /// \returns true if <tt>ptr</tt> is aligned on at least <tt>alignment</tt> boundary, false otherwise
1028 /// \details Internally the function tests whether alignment is 1. If so, the function returns true.
1029 /// If not, then the function effectively performs a modular reduction and returns true if the residue is 0
1030 inline bool IsAlignedOn(const void *ptr, unsigned int alignment)
1031 {
1032  return alignment==1 || (IsPowerOf2(alignment) ? ModPowerOf2((size_t)ptr, alignment) == 0 : (size_t)ptr % alignment == 0);
1033 }
1034 
1035 /// \brief Determines whether ptr is minimally aligned
1036 /// \tparam T class or type
1037 /// \param ptr the pointer to check for alignment
1038 /// \returns true if <tt>ptr</tt> is aligned to at least <tt>T</tt> boundary, false otherwise
1039 /// \details Internally the function calls IsAlignedOn with a second parameter of GetAlignmentOf<T>
1040 template <class T>
1041 inline bool IsAligned(const void *ptr)
1042 {
1043  return IsAlignedOn(ptr, GetAlignmentOf<T>());
1044 }
1045 
1046 #if defined(CRYPTOPP_LITTLE_ENDIAN)
1047  typedef LittleEndian NativeByteOrder;
1048 #elif defined(CRYPTOPP_BIG_ENDIAN)
1049  typedef BigEndian NativeByteOrder;
1050 #else
1051 # error "Unable to determine endian-ness"
1052 #endif
1053 
1054 /// \brief Returns NativeByteOrder as an enumerated ByteOrder value
1055 /// \returns LittleEndian if the native byte order is little-endian, and BigEndian if the
1056 /// native byte order is big-endian
1057 /// \details NativeByteOrder is a typedef depending on the platform. If CRYPTOPP_LITTLE_ENDIAN is
1058 /// set in config.h, then GetNativeByteOrder returns LittleEndian. If
1059 /// CRYPTOPP_BIG_ENDIAN is set, then GetNativeByteOrder returns BigEndian.
1060 /// \note There are other byte orders besides little- and big-endian, and they include bi-endian
1061 /// and PDP-endian. If a system is neither little-endian nor big-endian, then a compile time
1062 /// error occurs.
1064 {
1065  return NativeByteOrder::ToEnum();
1066 }
1067 
1068 /// \brief Determines whether order follows native byte ordering
1069 /// \param order the ordering being tested against native byte ordering
1070 /// \returns true if order follows native byte ordering, false otherwise
1071 inline bool NativeByteOrderIs(ByteOrder order)
1072 {
1073  return order == GetNativeByteOrder();
1074 }
1075 
1076 /// \brief Returns the direction the cipher is being operated
1077 /// \tparam T class or type
1078 /// \param obj the cipher object being queried
1079 /// \returns ENCRYPTION if the cipher obj is being operated in its forward direction,
1080 /// DECRYPTION otherwise
1081 /// \details A cipher can be operated in a "forward" direction (encryption) or a "reverse"
1082 /// direction (decryption). The operations do not have to be symmetric, meaning a second
1083 /// application of the transformation does not necessariy return the original message.
1084 /// That is, <tt>E(D(m))</tt> may not equal <tt>E(E(m))</tt>; and <tt>D(E(m))</tt> may not
1085 /// equal <tt>D(D(m))</tt>.
1086 template <class T>
1087 inline CipherDir GetCipherDir(const T &obj)
1088 {
1089  return obj.IsForwardTransformation() ? ENCRYPTION : DECRYPTION;
1090 }
1091 
1092 /// \brief Attempts to reclaim unused memory
1093 /// \throws bad_alloc
1094 /// \details In the normal course of running a program, a request for memory normally succeeds. If a
1095 /// call to AlignedAllocate or UnalignedAllocate fails, then CallNewHandler is called in
1096 /// an effort to recover. Internally, CallNewHandler calls set_new_handler(NULLPTR) in an effort
1097 /// to free memory. There is no guarantee CallNewHandler will be able to procure more memory so
1098 /// an allocation succeeds. If the call to set_new_handler fails, then CallNewHandler throws
1099 /// a bad_alloc exception.
1100 CRYPTOPP_DLL void CRYPTOPP_API CallNewHandler();
1101 
1102 /// \brief Performs an addition with carry on a block of bytes
1103 /// \param inout the byte block
1104 /// \param size the size of the block, in bytes
1105 /// \details Performs an addition with carry by adding 1 on a block of bytes starting at the least
1106 /// significant byte. Once carry is 0, the function terminates and returns to the caller.
1107 /// \note The function is not constant time because it stops processing when the carry is 0.
1108 inline void IncrementCounterByOne(byte *inout, unsigned int size)
1109 {
1110  CRYPTOPP_ASSERT(inout != NULLPTR); CRYPTOPP_ASSERT(size < INT_MAX);
1111  for (int i=int(size-1), carry=1; i>=0 && carry; i--)
1112  carry = !++inout[i];
1113 }
1114 
1115 /// \brief Performs an addition with carry on a block of bytes
1116 /// \param output the destination block of bytes
1117 /// \param input the source block of bytes
1118 /// \param size the size of the block
1119 /// \details Performs an addition with carry on a block of bytes starting at the least significant
1120 /// byte. Once carry is 0, the remaining bytes from input are copied to output using memcpy.
1121 /// \details The function is close to near-constant time because it operates on all the bytes in the blocks.
1122 inline void IncrementCounterByOne(byte *output, const byte *input, unsigned int size)
1123 {
1124  CRYPTOPP_ASSERT(output != NULLPTR); CRYPTOPP_ASSERT(input != NULLPTR); CRYPTOPP_ASSERT(size < INT_MAX);
1125 
1126  int i, carry;
1127  for (i=int(size-1), carry=1; i>=0 && carry; i--)
1128  carry = ((output[i] = input[i]+1) == 0);
1129  memcpy_s(output, size, input, size_t(i)+1);
1130 }
1131 
1132 /// \brief Performs a branchless swap of values a and b if condition c is true
1133 /// \tparam T class or type
1134 /// \param c the condition to perform the swap
1135 /// \param a the first value
1136 /// \param b the second value
1137 template <class T>
1138 inline void ConditionalSwap(bool c, T &a, T &b)
1139 {
1140  T t = c * (a ^ b);
1141  a ^= t;
1142  b ^= t;
1143 }
1144 
1145 /// \brief Performs a branchless swap of pointers a and b if condition c is true
1146 /// \tparam T class or type
1147 /// \param c the condition to perform the swap
1148 /// \param a the first pointer
1149 /// \param b the second pointer
1150 template <class T>
1151 inline void ConditionalSwapPointers(bool c, T &a, T &b)
1152 {
1153  ptrdiff_t t = size_t(c) * (a - b);
1154  a -= t;
1155  b += t;
1156 }
1157 
1158 // see http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/protect-secrets.html
1159 // and http://www.securecoding.cert.org/confluence/display/cplusplus/MSC06-CPP.+Be+aware+of+compiler+optimization+when+dealing+with+sensitive+data
1160 
1161 /// \brief Sets each element of an array to 0
1162 /// \tparam T class or type
1163 /// \param buf an array of elements
1164 /// \param n the number of elements in the array
1165 /// \details The operation performs a wipe or zeroization. The function attempts to survive optimizations and dead code removal
1166 template <class T>
1167 void SecureWipeBuffer(T *buf, size_t n)
1168 {
1169  // GCC 4.3.2 on Cygwin optimizes away the first store if this loop is done in the forward direction
1170  volatile T *p = buf+n;
1171  while (n--)
1172  *(--p) = 0;
1173 }
1174 
1175 #if (_MSC_VER >= 1400 || defined(__GNUC__)) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86)
1176 
1177 /// \brief Sets each byte of an array to 0
1178 /// \param buf an array of bytes
1179 /// \param n the number of elements in the array
1180 /// \details The operation performs a wipe or zeroization. The function attempts to survive optimizations and dead code removal.
1181 template<> inline void SecureWipeBuffer(byte *buf, size_t n)
1182 {
1183  volatile byte *p = buf;
1184 #ifdef __GNUC__
1185  asm volatile("rep stosb" : "+c"(n), "+D"(p) : "a"(0) : "memory");
1186 #else
1187  __stosb((byte *)(size_t)p, 0, n);
1188 #endif
1189 }
1190 
1191 /// \brief Sets each 16-bit element of an array to 0
1192 /// \param buf an array of 16-bit words
1193 /// \param n the number of elements in the array
1194 /// \details The operation performs a wipe or zeroization. The function attempts to survive optimizations and dead code removal.
1195 template<> inline void SecureWipeBuffer(word16 *buf, size_t n)
1196 {
1197  volatile word16 *p = buf;
1198 #ifdef __GNUC__
1199  asm volatile("rep stosw" : "+c"(n), "+D"(p) : "a"(0) : "memory");
1200 #else
1201  __stosw((word16 *)(size_t)p, 0, n);
1202 #endif
1203 }
1204 
1205 /// \brief Sets each 32-bit element of an array to 0
1206 /// \param buf an array of 32-bit words
1207 /// \param n the number of elements in the array
1208 /// \details The operation performs a wipe or zeroization. The function attempts to survive optimizations and dead code removal.
1209 template<> inline void SecureWipeBuffer(word32 *buf, size_t n)
1210 {
1211  volatile word32 *p = buf;
1212 #ifdef __GNUC__
1213  asm volatile("rep stosl" : "+c"(n), "+D"(p) : "a"(0) : "memory");
1214 #else
1215  __stosd((unsigned long *)(size_t)p, 0, n);
1216 #endif
1217 }
1218 
1219 /// \brief Sets each 64-bit element of an array to 0
1220 /// \param buf an array of 64-bit words
1221 /// \param n the number of elements in the array
1222 /// \details The operation performs a wipe or zeroization. The function attempts to survive optimizations and dead code removal.
1223 template<> inline void SecureWipeBuffer(word64 *buf, size_t n)
1224 {
1225 #if CRYPTOPP_BOOL_X64
1226  volatile word64 *p = buf;
1227 #ifdef __GNUC__
1228  asm volatile("rep stosq" : "+c"(n), "+D"(p) : "a"(0) : "memory");
1229 #else
1230  __stosq((word64 *)(size_t)p, 0, n);
1231 #endif
1232 #else
1233  SecureWipeBuffer((word32 *)buf, 2*n);
1234 #endif
1235 }
1236 
1237 #endif // #if (_MSC_VER >= 1400 || defined(__GNUC__)) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86)
1238 
1239 #if (_MSC_VER >= 1700) && defined(_M_ARM)
1240 template<> inline void SecureWipeBuffer(byte *buf, size_t n)
1241 {
1242  char *p = reinterpret_cast<char*>(buf+n);
1243  while (n--)
1244  __iso_volatile_store8(--p, 0);
1245 }
1246 
1247 template<> inline void SecureWipeBuffer(word16 *buf, size_t n)
1248 {
1249  short *p = reinterpret_cast<short*>(buf+n);
1250  while (n--)
1251  __iso_volatile_store16(--p, 0);
1252 }
1253 
1254 template<> inline void SecureWipeBuffer(word32 *buf, size_t n)
1255 {
1256  int *p = reinterpret_cast<int*>(buf+n);
1257  while (n--)
1258  __iso_volatile_store32(--p, 0);
1259 }
1260 
1261 template<> inline void SecureWipeBuffer(word64 *buf, size_t n)
1262 {
1263  __int64 *p = reinterpret_cast<__int64*>(buf+n);
1264  while (n--)
1265  __iso_volatile_store64(--p, 0);
1266 }
1267 #endif
1268 
1269 /// \brief Sets each element of an array to 0
1270 /// \tparam T class or type
1271 /// \param buf an array of elements
1272 /// \param n the number of elements in the array
1273 /// \details The operation performs a wipe or zeroization. The function attempts to survive optimizations and dead code removal.
1274 template <class T>
1275 inline void SecureWipeArray(T *buf, size_t n)
1276 {
1277  if (sizeof(T) % 8 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word64>() == 0)
1278  SecureWipeBuffer((word64 *)(void *)buf, n * (sizeof(T)/8));
1279  else if (sizeof(T) % 4 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word32>() == 0)
1280  SecureWipeBuffer((word32 *)(void *)buf, n * (sizeof(T)/4));
1281  else if (sizeof(T) % 2 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word16>() == 0)
1282  SecureWipeBuffer((word16 *)(void *)buf, n * (sizeof(T)/2));
1283  else
1284  SecureWipeBuffer((byte *)(void *)buf, n * sizeof(T));
1285 }
1286 
1287 /// \brief Converts a wide character C-string to a multibyte string
1288 /// \param str C-string consisting of wide characters
1289 /// \param throwOnError flag indicating the function should throw on error
1290 /// \returns str converted to a multibyte string or an empty string.
1291 /// \details StringNarrow() converts a wide string to a narrow string using C++ std::wcstombs() under
1292 /// the executing thread's locale. A locale must be set before using this function, and it can be
1293 /// set with std::setlocale() if needed. Upon success, the converted string is returned.
1294 /// \details Upon failure with throwOnError as false, the function returns an empty string. If
1295 /// throwOnError as true, the function throws an InvalidArgument() exception.
1296 /// \note If you try to convert, say, the Chinese character for "bone" from UTF-16 (0x9AA8) to UTF-8
1297 /// (0xE9 0xAA 0xA8), then you must ensure the locale is available. If the locale is not available,
1298 /// then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception.
1299 std::string StringNarrow(const wchar_t *str, bool throwOnError = true);
1300 
1301 /// \brief Converts a multibyte C-string to a wide character string
1302 /// \param str C-string consisting of wide characters
1303 /// \param throwOnError flag indicating the function should throw on error
1304 /// \returns str converted to a multibyte string or an empty string.
1305 /// \details StringWiden() converts a narrow string to a wide string using C++ std::mbstowcs() under
1306 /// the executing thread's locale. A locale must be set before using this function, and it can be
1307 /// set with std::setlocale() if needed. Upon success, the converted string is returned.
1308 /// \details Upon failure with throwOnError as false, the function returns an empty string. If
1309 /// throwOnError as true, the function throws an InvalidArgument() exception.
1310 /// \note If you try to convert, say, the Chinese character for "bone" from UTF-8 (0xE9 0xAA 0xA8)
1311 /// to UTF-16 (0x9AA8), then you must ensure the locale is available. If the locale is not available,
1312 /// then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception.
1313 std::wstring StringWiden(const char *str, bool throwOnError = true);
1314 
1315 #ifdef CRYPTOPP_DOXYGEN_PROCESSING
1316 
1317 /// \brief Allocates a buffer on 16-byte boundary
1318 /// \param size the size of the buffer
1319 /// \details AlignedAllocate is primarily used when the data will be proccessed by MMX, SSE2 and NEON
1320 /// instructions. The assembly language routines rely on the alignment. If the alignment is not
1321 /// respected, then a SIGBUS could be generated on Unix and Linux, and an
1322 /// EXCEPTION_DATATYPE_MISALIGNMENT could be generated on Windows.
1323 /// \note AlignedAllocate and AlignedDeallocate are available when CRYPTOPP_BOOL_ALIGN16 is
1324 /// defined. CRYPTOPP_BOOL_ALIGN16 is defined in config.h
1325 CRYPTOPP_DLL void* CRYPTOPP_API AlignedAllocate(size_t size);
1326 
1327 /// \brief Frees a buffer allocated with AlignedAllocate
1328 /// \param ptr the buffer to free
1329 /// \note AlignedAllocate and AlignedDeallocate are available when CRYPTOPP_BOOL_ALIGN16 is
1330 /// defined. CRYPTOPP_BOOL_ALIGN16 is defined in config.h
1331 CRYPTOPP_DLL void CRYPTOPP_API AlignedDeallocate(void *ptr);
1332 
1333 #endif // CRYPTOPP_DOXYGEN_PROCESSING
1334 
1335 #if CRYPTOPP_BOOL_ALIGN16
1336 CRYPTOPP_DLL void* CRYPTOPP_API AlignedAllocate(size_t size);
1337 CRYPTOPP_DLL void CRYPTOPP_API AlignedDeallocate(void *ptr);
1338 #endif // CRYPTOPP_BOOL_ALIGN16
1339 
1340 /// \brief Allocates a buffer
1341 /// \param size the size of the buffer
1342 CRYPTOPP_DLL void * CRYPTOPP_API UnalignedAllocate(size_t size);
1343 
1344 /// \brief Frees a buffer allocated with UnalignedAllocate
1345 /// \param ptr the buffer to free
1346 CRYPTOPP_DLL void CRYPTOPP_API UnalignedDeallocate(void *ptr);
1347 
1348 // ************** rotate functions ***************
1349 
1350 /// \brief Performs a left rotate
1351 /// \tparam R the number of bit positions to rotate the value
1352 /// \tparam T the word type
1353 /// \param x the value to rotate
1354 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1355 /// \details R must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1356 /// Use rotlMod if the rotate amount R is outside the range.
1357 /// \details Use rotlConstant when the rotate amount is constant. The template function was added
1358 /// because Clang did not propagate the constant when passed as a function parameter. Clang's
1359 /// need for a constexpr meant rotlFixed failed to compile on occassion.
1360 /// \note rotlConstant attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1361 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1362 /// counterparts.
1363 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1364 /// \since Crypto++ 6.0
1365 template <unsigned int R, class T> inline T rotlConstant(T x)
1366 {
1367  // Portable rotate that reduces to single instruction...
1368  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
1369  // http://software.intel.com/en-us/forums/topic/580884
1370  // and http://llvm.org/bugs/show_bug.cgi?id=24226
1371  static const unsigned int THIS_SIZE = sizeof(T)*8;
1372  static const unsigned int MASK = THIS_SIZE-1;
1373  CRYPTOPP_ASSERT(R < THIS_SIZE);
1374  return T((x<<R)|(x>>(-R&MASK)));
1375 }
1376 
1377 /// \brief Performs a right rotate
1378 /// \tparam R the number of bit positions to rotate the value
1379 /// \tparam T the word type
1380 /// \param x the value to rotate
1381 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1382 /// \details R must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1383 /// Use rotrMod if the rotate amount R is outside the range.
1384 /// \details Use rotrConstant when the rotate amount is constant. The template function was added
1385 /// because Clang did not propagate the constant when passed as a function parameter. Clang's
1386 /// need for a constexpr meant rotrFixed failed to compile on occassion.
1387 /// \note rotrConstant attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1388 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1389 /// counterparts.
1390 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1391 template <unsigned int R, class T> inline T rotrConstant(T x)
1392 {
1393  // Portable rotate that reduces to single instruction...
1394  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
1395  // http://software.intel.com/en-us/forums/topic/580884
1396  // and http://llvm.org/bugs/show_bug.cgi?id=24226
1397  static const unsigned int THIS_SIZE = sizeof(T)*8;
1398  static const unsigned int MASK = THIS_SIZE-1;
1399  CRYPTOPP_ASSERT(R < THIS_SIZE);
1400  return T((x >> R)|(x<<(-R&MASK)));
1401 }
1402 
1403 /// \brief Performs a left rotate
1404 /// \tparam T the word type
1405 /// \param x the value to rotate
1406 /// \param y the number of bit positions to rotate the value
1407 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1408 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1409 /// Use rotlMod if the rotate amount y is outside the range.
1410 /// \note rotlFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1411 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1412 /// counterparts. New code should use <tt>rotlConstant</tt>, which accepts the rotate amount as a
1413 /// template parameter.
1414 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1415 /// \since Crypto++ 6.0
1416 template <class T> inline T rotlFixed(T x, unsigned int y)
1417 {
1418  // Portable rotate that reduces to single instruction...
1419  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
1420  // http://software.intel.com/en-us/forums/topic/580884
1421  // and http://llvm.org/bugs/show_bug.cgi?id=24226
1422  static const unsigned int THIS_SIZE = sizeof(T)*8;
1423  static const unsigned int MASK = THIS_SIZE-1;
1424  CRYPTOPP_ASSERT(y < THIS_SIZE);
1425  return T((x<<y)|(x>>(-y&MASK)));
1426 }
1427 
1428 /// \brief Performs a right rotate
1429 /// \tparam T the word type
1430 /// \param x the value to rotate
1431 /// \param y the number of bit positions to rotate the value
1432 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1433 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1434 /// Use rotrMod if the rotate amount y is outside the range.
1435 /// \note rotrFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1436 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1437 /// counterparts. New code should use <tt>rotrConstant</tt>, which accepts the rotate amount as a
1438 /// template parameter.
1439 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1440 /// \since Crypto++ 3.0
1441 template <class T> inline T rotrFixed(T x, unsigned int y)
1442 {
1443  // Portable rotate that reduces to single instruction...
1444  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
1445  // http://software.intel.com/en-us/forums/topic/580884
1446  // and http://llvm.org/bugs/show_bug.cgi?id=24226
1447  static const unsigned int THIS_SIZE = sizeof(T)*8;
1448  static const unsigned int MASK = THIS_SIZE-1;
1449  CRYPTOPP_ASSERT(y < THIS_SIZE);
1450  return T((x >> y)|(x<<(-y&MASK)));
1451 }
1452 
1453 /// \brief Performs a left rotate
1454 /// \tparam T the word type
1455 /// \param x the value to rotate
1456 /// \param y the number of bit positions to rotate the value
1457 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1458 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1459 /// Use rotlMod if the rotate amount y is outside the range.
1460 /// \note rotlVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1461 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1462 /// counterparts.
1463 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1464 /// \since Crypto++ 3.0
1465 template <class T> inline T rotlVariable(T x, unsigned int y)
1466 {
1467  static const unsigned int THIS_SIZE = sizeof(T)*8;
1468  static const unsigned int MASK = THIS_SIZE-1;
1469  CRYPTOPP_ASSERT(y < THIS_SIZE);
1470  return T((x<<y)|(x>>(-y&MASK)));
1471 }
1472 
1473 /// \brief Performs a right rotate
1474 /// \tparam T the word type
1475 /// \param x the value to rotate
1476 /// \param y the number of bit positions to rotate the value
1477 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1478 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1479 /// Use rotrMod if the rotate amount y is outside the range.
1480 /// \note rotrVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1481 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1482 /// counterparts.
1483 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1484 /// \since Crypto++ 3.0
1485 template <class T> inline T rotrVariable(T x, unsigned int y)
1486 {
1487  static const unsigned int THIS_SIZE = sizeof(T)*8;
1488  static const unsigned int MASK = THIS_SIZE-1;
1489  CRYPTOPP_ASSERT(y < THIS_SIZE);
1490  return T((x>>y)|(x<<(-y&MASK)));
1491 }
1492 
1493 /// \brief Performs a left rotate
1494 /// \tparam T the word type
1495 /// \param x the value to rotate
1496 /// \param y the number of bit positions to rotate the value
1497 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1498 /// \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1499 /// \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>.
1500 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1501 /// \since Crypto++ 3.0
1502 template <class T> inline T rotlMod(T x, unsigned int y)
1503 {
1504  static const unsigned int THIS_SIZE = sizeof(T)*8;
1505  static const unsigned int MASK = THIS_SIZE-1;
1506  return T((x<<(y&MASK))|(x>>(-y&MASK)));
1507 }
1508 
1509 /// \brief Performs a right rotate
1510 /// \tparam T the word type
1511 /// \param x the value to rotate
1512 /// \param y the number of bit positions to rotate the value
1513 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1514 /// \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1515 /// \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>.
1516 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1517 /// \since Crypto++ 3.0
1518 template <class T> inline T rotrMod(T x, unsigned int y)
1519 {
1520  static const unsigned int THIS_SIZE = sizeof(T)*8;
1521  static const unsigned int MASK = THIS_SIZE-1;
1522  return T((x>>(y&MASK))|(x<<(-y&MASK)));
1523 }
1524 
1525 #ifdef _MSC_VER
1526 
1527 /// \brief Performs a left rotate
1528 /// \tparam T the word type
1529 /// \param x the 32-bit value to rotate
1530 /// \param y the number of bit positions to rotate the value
1531 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1532 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1533 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1534 /// \note rotlFixed will assert in Debug builds if is outside the allowed range.
1535 /// \since Crypto++ 3.0
1536 template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y)
1537 {
1538  // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
1539  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1540  return y ? _lrotl(x, static_cast<byte>(y)) : x;
1541 }
1542 
1543 /// \brief Performs a right rotate
1544 /// \tparam T the word type
1545 /// \param x the 32-bit value to rotate
1546 /// \param y the number of bit positions to rotate the value
1547 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1548 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1549 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1550 /// \note rotrFixed will assert in Debug builds if is outside the allowed range.
1551 /// \since Crypto++ 3.0
1552 template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y)
1553 {
1554  // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
1555  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1556  return y ? _lrotr(x, static_cast<byte>(y)) : x;
1557 }
1558 
1559 /// \brief Performs a left rotate
1560 /// \tparam T the word type
1561 /// \param x the 32-bit value to rotate
1562 /// \param y the number of bit positions to rotate the value
1563 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1564 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1565 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1566 /// \note rotlVariable will assert in Debug builds if is outside the allowed range.
1567 /// \since Crypto++ 3.0
1568 template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y)
1569 {
1570  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1571  return _lrotl(x, static_cast<byte>(y));
1572 }
1573 
1574 /// \brief Performs a right rotate
1575 /// \tparam T the word type
1576 /// \param x the 32-bit value to rotate
1577 /// \param y the number of bit positions to rotate the value
1578 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1579 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1580 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1581 /// \note rotrVariable will assert in Debug builds if is outside the allowed range.
1582 /// \since Crypto++ 3.0
1583 template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y)
1584 {
1585  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1586  return _lrotr(x, static_cast<byte>(y));
1587 }
1588 
1589 /// \brief Performs a left rotate
1590 /// \tparam T the word type
1591 /// \param x the 32-bit value to rotate
1592 /// \param y the number of bit positions to rotate the value
1593 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1594 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1595 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1596 /// \since Crypto++ 3.0
1597 template<> inline word32 rotlMod<word32>(word32 x, unsigned int y)
1598 {
1599  y %= 8*sizeof(x);
1600  return _lrotl(x, static_cast<byte>(y));
1601 }
1602 
1603 /// \brief Performs a right rotate
1604 /// \tparam T the word type
1605 /// \param x the 32-bit value to rotate
1606 /// \param y the number of bit positions to rotate the value
1607 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1608 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1609 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1610 /// \since Crypto++ 3.0
1611 template<> inline word32 rotrMod<word32>(word32 x, unsigned int y)
1612 {
1613  y %= 8*sizeof(x);
1614  return _lrotr(x, static_cast<byte>(y));
1615 }
1616 
1617 #endif // #ifdef _MSC_VER
1618 
1619 #if (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
1620 // Intel C++ Compiler 10.0 calls a function instead of using the rotate instruction when using these instructions
1621 
1622 /// \brief Performs a left rotate
1623 /// \tparam T the word type
1624 /// \param x the 64-bit value to rotate
1625 /// \param y the number of bit positions to rotate the value
1626 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1627 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1628 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1629 /// \note rotrFixed will assert in Debug builds if is outside the allowed range.
1630 /// \since Crypto++ 3.0
1631 template<> inline word64 rotlFixed<word64>(word64 x, unsigned int y)
1632 {
1633  // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
1634  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1635  return y ? _rotl64(x, static_cast<byte>(y)) : x;
1636 }
1637 
1638 /// \brief Performs a right rotate
1639 /// \tparam T the word type
1640 /// \param x the 64-bit value to rotate
1641 /// \param y the number of bit positions to rotate the value
1642 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1643 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1644 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1645 /// \note rotrFixed will assert in Debug builds if is outside the allowed range.
1646 /// \since Crypto++ 3.0
1647 template<> inline word64 rotrFixed<word64>(word64 x, unsigned int y)
1648 {
1649  // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
1650  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1651  return y ? _rotr64(x, static_cast<byte>(y)) : x;
1652 }
1653 
1654 /// \brief Performs a left rotate
1655 /// \tparam T the word type
1656 /// \param x the 64-bit value to rotate
1657 /// \param y the number of bit positions to rotate the value
1658 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1659 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1660 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1661 /// \note rotlVariable will assert in Debug builds if is outside the allowed range.
1662 /// \since Crypto++ 3.0
1663 template<> inline word64 rotlVariable<word64>(word64 x, unsigned int y)
1664 {
1665  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1666  return _rotl64(x, static_cast<byte>(y));
1667 }
1668 
1669 /// \brief Performs a right rotate
1670 /// \tparam T the word type
1671 /// \param x the 64-bit value to rotate
1672 /// \param y the number of bit positions to rotate the value
1673 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1674 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1675 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1676 /// \note rotrVariable will assert in Debug builds if is outside the allowed range.
1677 /// \since Crypto++ 3.0
1678 template<> inline word64 rotrVariable<word64>(word64 x, unsigned int y)
1679 {
1680  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1681  return y ? _rotr64(x, static_cast<byte>(y)) : x;
1682 }
1683 
1684 /// \brief Performs a left rotate
1685 /// \tparam T the word type
1686 /// \param x the 64-bit value to rotate
1687 /// \param y the number of bit positions to rotate the value
1688 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1689 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1690 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1691 /// \since Crypto++ 3.0
1692 template<> inline word64 rotlMod<word64>(word64 x, unsigned int y)
1693 {
1694  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1695  return y ? _rotl64(x, static_cast<byte>(y)) : x;
1696 }
1697 
1698 /// \brief Performs a right rotate
1699 /// \tparam T the word type
1700 /// \param x the 64-bit value to rotate
1701 /// \param y the number of bit positions to rotate the value
1702 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1703 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1704 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1705 /// \since Crypto++ 3.0
1706 template<> inline word64 rotrMod<word64>(word64 x, unsigned int y)
1707 {
1708  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1709  return y ? _rotr64(x, static_cast<byte>(y)) : x;
1710 }
1711 
1712 #endif // #if _MSC_VER >= 1310
1713 
1714 #if _MSC_VER >= 1400 && !defined(__INTEL_COMPILER)
1715 // Intel C++ Compiler 10.0 gives undefined externals with these
1716 template<> inline word16 rotlFixed<word16>(word16 x, unsigned int y)
1717 {
1718  // Intrinsic, not bound to C/C++ language rules.
1719  return _rotl16(x, static_cast<byte>(y));
1720 }
1721 
1722 template<> inline word16 rotrFixed<word16>(word16 x, unsigned int y)
1723 {
1724  // Intrinsic, not bound to C/C++ language rules.
1725  return _rotr16(x, static_cast<byte>(y));
1726 }
1727 
1728 template<> inline word16 rotlVariable<word16>(word16 x, unsigned int y)
1729 {
1730  return _rotl16(x, static_cast<byte>(y));
1731 }
1732 
1733 template<> inline word16 rotrVariable<word16>(word16 x, unsigned int y)
1734 {
1735  return _rotr16(x, static_cast<byte>(y));
1736 }
1737 
1738 template<> inline word16 rotlMod<word16>(word16 x, unsigned int y)
1739 {
1740  return _rotl16(x, static_cast<byte>(y));
1741 }
1742 
1743 template<> inline word16 rotrMod<word16>(word16 x, unsigned int y)
1744 {
1745  return _rotr16(x, static_cast<byte>(y));
1746 }
1747 
1748 template<> inline byte rotlFixed<byte>(byte x, unsigned int y)
1749 {
1750  // Intrinsic, not bound to C/C++ language rules.
1751  return _rotl8(x, static_cast<byte>(y));
1752 }
1753 
1754 template<> inline byte rotrFixed<byte>(byte x, unsigned int y)
1755 {
1756  // Intrinsic, not bound to C/C++ language rules.
1757  return _rotr8(x, static_cast<byte>(y));
1758 }
1759 
1760 template<> inline byte rotlVariable<byte>(byte x, unsigned int y)
1761 {
1762  return _rotl8(x, static_cast<byte>(y));
1763 }
1764 
1765 template<> inline byte rotrVariable<byte>(byte x, unsigned int y)
1766 {
1767  return _rotr8(x, static_cast<byte>(y));
1768 }
1769 
1770 template<> inline byte rotlMod<byte>(byte x, unsigned int y)
1771 {
1772  return _rotl8(x, static_cast<byte>(y));
1773 }
1774 
1775 template<> inline byte rotrMod<byte>(byte x, unsigned int y)
1776 {
1777  return _rotr8(x, static_cast<byte>(y));
1778 }
1779 
1780 #endif // #if _MSC_VER >= 1400
1781 
1782 #if (defined(__MWERKS__) && TARGET_CPU_PPC)
1783 
1784 template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y)
1785 {
1786  CRYPTOPP_ASSERT(y < 32);
1787  return y ? __rlwinm(x,y,0,31) : x;
1788 }
1789 
1790 template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y)
1791 {
1792  CRYPTOPP_ASSERT(y < 32);
1793  return y ? __rlwinm(x,32-y,0,31) : x;
1794 }
1795 
1796 template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y)
1797 {
1798  CRYPTOPP_ASSERT(y < 32);
1799  return (__rlwnm(x,y,0,31));
1800 }
1801 
1802 template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y)
1803 {
1804  CRYPTOPP_ASSERT(y < 32);
1805  return (__rlwnm(x,32-y,0,31));
1806 }
1807 
1808 template<> inline word32 rotlMod<word32>(word32 x, unsigned int y)
1809 {
1810  return (__rlwnm(x,y,0,31));
1811 }
1812 
1813 template<> inline word32 rotrMod<word32>(word32 x, unsigned int y)
1814 {
1815  return (__rlwnm(x,32-y,0,31));
1816 }
1817 
1818 #endif // #if (defined(__MWERKS__) && TARGET_CPU_PPC)
1819 
1820 // ************** endian reversal ***************
1821 
1822 /// \brief Gets a byte from a value
1823 /// \param order the ByteOrder of the value
1824 /// \param value the value to retrieve the byte
1825 /// \param index the location of the byte to retrieve
1826 template <class T>
1827 inline unsigned int GetByte(ByteOrder order, T value, unsigned int index)
1828 {
1829  if (order == LITTLE_ENDIAN_ORDER)
1830  return GETBYTE(value, index);
1831  else
1832  return GETBYTE(value, sizeof(T)-index-1);
1833 }
1834 
1835 /// \brief Reverses bytes in a 8-bit value
1836 /// \param value the 8-bit value to reverse
1837 /// \note ByteReverse returns the value passed to it since there is nothing to reverse
1838 inline byte ByteReverse(byte value)
1839 {
1840  return value;
1841 }
1842 
1843 /// \brief Reverses bytes in a 16-bit value
1844 /// \param value the 16-bit value to reverse
1845 /// \details ByteReverse calls bswap if available. Otherwise the function performs a 8-bit rotate on the word16
1846 inline word16 ByteReverse(word16 value)
1847 {
1848 #if defined(CRYPTOPP_BYTESWAP_AVAILABLE)
1849  return bswap_16(value);
1850 #elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
1851  return _byteswap_ushort(value);
1852 #else
1853  return rotlFixed(value, 8U);
1854 #endif
1855 }
1856 
1857 /// \brief Reverses bytes in a 32-bit value
1858 /// \param value the 32-bit value to reverse
1859 /// \details ByteReverse calls bswap if available. Otherwise the function uses a combination of rotates on the word32
1860 inline word32 ByteReverse(word32 value)
1861 {
1862 #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
1863  __asm__ ("bswap %0" : "=r" (value) : "0" (value));
1864  return value;
1865 #elif defined(CRYPTOPP_BYTESWAP_AVAILABLE)
1866  return bswap_32(value);
1867 #elif defined(__MWERKS__) && TARGET_CPU_PPC
1868  return (word32)__lwbrx(&value,0);
1869 #elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
1870  return _byteswap_ulong(value);
1871 #elif CRYPTOPP_FAST_ROTATE(32) && !defined(__xlC__)
1872  // 5 instructions with rotate instruction, 9 without
1873  return (rotrFixed(value, 8U) & 0xff00ff00) | (rotlFixed(value, 8U) & 0x00ff00ff);
1874 #else
1875  // 6 instructions with rotate instruction, 8 without
1876  value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
1877  return rotlFixed(value, 16U);
1878 #endif
1879 }
1880 
1881 /// \brief Reverses bytes in a 64-bit value
1882 /// \param value the 64-bit value to reverse
1883 /// \details ByteReverse calls bswap if available. Otherwise the function uses a combination of rotates on the word64
1884 inline word64 ByteReverse(word64 value)
1885 {
1886 #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE) && defined(__x86_64__)
1887  __asm__ ("bswap %0" : "=r" (value) : "0" (value));
1888  return value;
1889 #elif defined(CRYPTOPP_BYTESWAP_AVAILABLE)
1890  return bswap_64(value);
1891 #elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
1892  return _byteswap_uint64(value);
1893 #elif CRYPTOPP_BOOL_SLOW_WORD64
1894  return (word64(ByteReverse(word32(value))) << 32) | ByteReverse(word32(value>>32));
1895 #else
1896  value = ((value & W64LIT(0xFF00FF00FF00FF00)) >> 8) | ((value & W64LIT(0x00FF00FF00FF00FF)) << 8);
1897  value = ((value & W64LIT(0xFFFF0000FFFF0000)) >> 16) | ((value & W64LIT(0x0000FFFF0000FFFF)) << 16);
1898  return rotlFixed(value, 32U);
1899 #endif
1900 }
1901 
1902 /// \brief Reverses bits in a 8-bit value
1903 /// \param value the 8-bit value to reverse
1904 /// \details BitReverse performs a combination of shifts on the byte
1905 inline byte BitReverse(byte value)
1906 {
1907  value = byte((value & 0xAA) >> 1) | byte((value & 0x55) << 1);
1908  value = byte((value & 0xCC) >> 2) | byte((value & 0x33) << 2);
1909  return rotlFixed(value, 4U);
1910 }
1911 
1912 /// \brief Reverses bits in a 16-bit value
1913 /// \param value the 16-bit value to reverse
1914 /// \details BitReverse performs a combination of shifts on the word16
1915 inline word16 BitReverse(word16 value)
1916 {
1917  value = word16((value & 0xAAAA) >> 1) | word16((value & 0x5555) << 1);
1918  value = word16((value & 0xCCCC) >> 2) | word16((value & 0x3333) << 2);
1919  value = word16((value & 0xF0F0) >> 4) | word16((value & 0x0F0F) << 4);
1920  return ByteReverse(value);
1921 }
1922 
1923 /// \brief Reverses bits in a 32-bit value
1924 /// \param value the 32-bit value to reverse
1925 /// \details BitReverse performs a combination of shifts on the word32
1926 inline word32 BitReverse(word32 value)
1927 {
1928  value = word32((value & 0xAAAAAAAA) >> 1) | word32((value & 0x55555555) << 1);
1929  value = word32((value & 0xCCCCCCCC) >> 2) | word32((value & 0x33333333) << 2);
1930  value = word32((value & 0xF0F0F0F0) >> 4) | word32((value & 0x0F0F0F0F) << 4);
1931  return ByteReverse(value);
1932 }
1933 
1934 /// \brief Reverses bits in a 64-bit value
1935 /// \param value the 64-bit value to reverse
1936 /// \details BitReverse performs a combination of shifts on the word64
1937 inline word64 BitReverse(word64 value)
1938 {
1939 #if CRYPTOPP_BOOL_SLOW_WORD64
1940  return (word64(BitReverse(word32(value))) << 32) | BitReverse(word32(value>>32));
1941 #else
1942  value = word64((value & W64LIT(0xAAAAAAAAAAAAAAAA)) >> 1) | word64((value & W64LIT(0x5555555555555555)) << 1);
1943  value = word64((value & W64LIT(0xCCCCCCCCCCCCCCCC)) >> 2) | word64((value & W64LIT(0x3333333333333333)) << 2);
1944  value = word64((value & W64LIT(0xF0F0F0F0F0F0F0F0)) >> 4) | word64((value & W64LIT(0x0F0F0F0F0F0F0F0F)) << 4);
1945  return ByteReverse(value);
1946 #endif
1947 }
1948 
1949 /// \brief Reverses bits in a value
1950 /// \param value the value to reverse
1951 /// \details The template overload of BitReverse operates on signed and unsigned values.
1952 /// Internally the size of T is checked, and then value is cast to a byte,
1953 /// word16, word32 or word64. After the cast, the appropriate BitReverse
1954 /// overload is called.
1955 template <class T>
1956 inline T BitReverse(T value)
1957 {
1958  if (sizeof(T) == 1)
1959  return (T)BitReverse((byte)value);
1960  else if (sizeof(T) == 2)
1961  return (T)BitReverse((word16)value);
1962  else if (sizeof(T) == 4)
1963  return (T)BitReverse((word32)value);
1964  else
1965  {
1966  CRYPTOPP_ASSERT(sizeof(T) == 8);
1967  return (T)BitReverse((word64)value);
1968  }
1969 }
1970 
1971 /// \brief Reverses bytes in a value depending upon endianness
1972 /// \tparam T the class or type
1973 /// \param order the ByteOrder of the data
1974 /// \param value the value to conditionally reverse
1975 /// \details Internally, the ConditionalByteReverse calls NativeByteOrderIs.
1976 /// If order matches native byte order, then the original value is returned.
1977 /// If not, then ByteReverse is called on the value before returning to the caller.
1978 template <class T>
1979 inline T ConditionalByteReverse(ByteOrder order, T value)
1980 {
1981  return NativeByteOrderIs(order) ? value : ByteReverse(value);
1982 }
1983 
1984 /// \brief Reverses bytes in an element from an array of elements
1985 /// \tparam T the class or type
1986 /// \param out the output array of elements
1987 /// \param in the input array of elements
1988 /// \param byteCount the total number of bytes in the array
1989 /// \details Internally, ByteReverse visits each element in the in array
1990 /// calls ByteReverse on it, and writes the result to out.
1991 /// \details ByteReverse does not process tail byes, or bytes that are
1992 /// not part of a full element. If T is int (and int is 4 bytes), then
1993 /// <tt>byteCount = 10</tt> means only the first 2 elements or 8 bytes are
1994 /// reversed.
1995 /// \details The follwoing program should help illustrate the behavior.
1996 /// <pre>vector<word32> v1, v2;
1997 ///
1998 /// v1.push_back(1);
1999 /// v1.push_back(2);
2000 /// v1.push_back(3);
2001 /// v1.push_back(4);
2002 ///
2003 /// v2.resize(v1.size());
2004 /// ByteReverse<word32>(&v2[0], &v1[0], 16);
2005 ///
2006 /// cout << "V1: ";
2007 /// for(unsigned int i = 0; i < v1.size(); i++)
2008 /// cout << std::hex << v1[i] << " ";
2009 /// cout << endl;
2010 ///
2011 /// cout << "V2: ";
2012 /// for(unsigned int i = 0; i < v2.size(); i++)
2013 /// cout << std::hex << v2[i] << " ";
2014 /// cout << endl;</pre>
2015 /// The program above results in the follwoing output.
2016 /// <pre>V1: 00000001 00000002 00000003 00000004
2017 /// V2: 01000000 02000000 03000000 04000000</pre>
2018 /// \sa ConditionalByteReverse
2019 template <class T>
2020 void ByteReverse(T *out, const T *in, size_t byteCount)
2021 {
2022  CRYPTOPP_ASSERT(byteCount % sizeof(T) == 0);
2023  size_t count = byteCount/sizeof(T);
2024  for (size_t i=0; i<count; i++)
2025  out[i] = ByteReverse(in[i]);
2026 }
2027 
2028 /// \brief Conditionally reverses bytes in an element from an array of elements
2029 /// \tparam T the class or type
2030 /// \param order the ByteOrder of the data
2031 /// \param out the output array of elements
2032 /// \param in the input array of elements
2033 /// \param byteCount the byte count of the arrays
2034 /// \details Internally, ByteReverse visits each element in the in array
2035 /// calls ByteReverse on it depending on the desired endianness, and writes the result to out.
2036 /// \details ByteReverse does not process tail byes, or bytes that are
2037 /// not part of a full element. If T is int (and int is 4 bytes), then
2038 /// <tt>byteCount = 10</tt> means only the first 2 elements or 8 bytes are
2039 /// reversed.
2040 /// \sa ByteReverse
2041 template <class T>
2042 inline void ConditionalByteReverse(ByteOrder order, T *out, const T *in, size_t byteCount)
2043 {
2044  if (!NativeByteOrderIs(order))
2045  ByteReverse(out, in, byteCount);
2046  else if (in != out)
2047  memcpy_s(out, byteCount, in, byteCount);
2048 }
2049 
2050 template <class T>
2051 inline void GetUserKey(ByteOrder order, T *out, size_t outlen, const byte *in, size_t inlen)
2052 {
2053  const size_t U = sizeof(T);
2054  CRYPTOPP_ASSERT(inlen <= outlen*U);
2055  memcpy_s(out, outlen*U, in, inlen);
2056  memset_z((byte *)out+inlen, 0, outlen*U-inlen);
2057  ConditionalByteReverse(order, out, out, RoundUpToMultipleOf(inlen, U));
2058 }
2059 
2060 #ifndef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
2061 inline byte UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const byte *)
2062 {
2063  CRYPTOPP_UNUSED(order);
2064  return block[0];
2065 }
2066 
2067 inline word16 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word16 *)
2068 {
2069  return (order == BIG_ENDIAN_ORDER)
2070  ? block[1] | (block[0] << 8)
2071  : block[0] | (block[1] << 8);
2072 }
2073 
2074 inline word32 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word32 *)
2075 {
2076  return (order == BIG_ENDIAN_ORDER)
2077  ? word32(block[3]) | (word32(block[2]) << 8) | (word32(block[1]) << 16) | (word32(block[0]) << 24)
2078  : word32(block[0]) | (word32(block[1]) << 8) | (word32(block[2]) << 16) | (word32(block[3]) << 24);
2079 }
2080 
2081 inline word64 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word64 *)
2082 {
2083  return (order == BIG_ENDIAN_ORDER)
2084  ?
2085  (word64(block[7]) |
2086  (word64(block[6]) << 8) |
2087  (word64(block[5]) << 16) |
2088  (word64(block[4]) << 24) |
2089  (word64(block[3]) << 32) |
2090  (word64(block[2]) << 40) |
2091  (word64(block[1]) << 48) |
2092  (word64(block[0]) << 56))
2093  :
2094  (word64(block[0]) |
2095  (word64(block[1]) << 8) |
2096  (word64(block[2]) << 16) |
2097  (word64(block[3]) << 24) |
2098  (word64(block[4]) << 32) |
2099  (word64(block[5]) << 40) |
2100  (word64(block[6]) << 48) |
2101  (word64(block[7]) << 56));
2102 }
2103 
2104 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, byte value, const byte *xorBlock)
2105 {
2106  CRYPTOPP_UNUSED(order);
2107  block[0] = (byte)(xorBlock ? (value ^ xorBlock[0]) : value);
2108 }
2109 
2110 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word16 value, const byte *xorBlock)
2111 {
2112  if (order == BIG_ENDIAN_ORDER)
2113  {
2114  if (xorBlock)
2115  {
2116  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2117  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2118  }
2119  else
2120  {
2121  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2122  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2123  }
2124  }
2125  else
2126  {
2127  if (xorBlock)
2128  {
2129  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2130  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2131  }
2132  else
2133  {
2134  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2135  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2136  }
2137  }
2138 }
2139 
2140 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word32 value, const byte *xorBlock)
2141 {
2142  if (order == BIG_ENDIAN_ORDER)
2143  {
2144  if (xorBlock)
2145  {
2146  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2147  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2148  block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2149  block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2150  }
2151  else
2152  {
2153  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2154  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2155  block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2156  block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2157  }
2158  }
2159  else
2160  {
2161  if (xorBlock)
2162  {
2163  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2164  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2165  block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2166  block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2167  }
2168  else
2169  {
2170  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2171  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2172  block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2173  block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2174  }
2175  }
2176 }
2177 
2178 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word64 value, const byte *xorBlock)
2179 {
2180  if (order == BIG_ENDIAN_ORDER)
2181  {
2182  if (xorBlock)
2183  {
2184  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
2185  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
2186  block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
2187  block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
2188  block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2189  block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2190  block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2191  block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2192  }
2193  else
2194  {
2195  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
2196  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
2197  block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
2198  block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
2199  block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2200  block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2201  block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2202  block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2203  }
2204  }
2205  else
2206  {
2207  if (xorBlock)
2208  {
2209  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2210  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2211  block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2212  block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2213  block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
2214  block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
2215  block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
2216  block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
2217  }
2218  else
2219  {
2220  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2221  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2222  block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2223  block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2224  block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
2225  block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
2226  block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
2227  block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
2228  }
2229  }
2230 }
2231 #endif // #ifndef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
2232 
2233 /// \brief Access a block of memory
2234 /// \tparam T class or type
2235 /// \param assumeAligned flag indicating alignment
2236 /// \param order the ByteOrder of the data
2237 /// \param block the byte buffer to be processed
2238 /// \returns the word in the specified byte order
2239 /// \details GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates
2240 /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
2241 /// LITTLE_ENDIAN_ORDER.
2242 /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w</tt>
2243 /// will be <tt>0x03020100</tt>.
2244 /// <pre>
2245 /// word32 w;
2246 /// byte buffer[4] = {0,1,2,3};
2247 /// w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer);
2248 /// </pre>
2249 template <class T>
2250 inline T GetWord(bool assumeAligned, ByteOrder order, const byte *block)
2251 {
2252  CRYPTOPP_UNUSED(assumeAligned);
2253 #ifdef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
2254  return ConditionalByteReverse(order, *reinterpret_cast<const T *>((const void *)block));
2255 #else
2256  T temp;
2257  memcpy(&temp, block, sizeof(T));
2258  return ConditionalByteReverse(order, temp);
2259 #endif
2260 }
2261 
2262 /// \brief Access a block of memory
2263 /// \tparam T class or type
2264 /// \param assumeAligned flag indicating alignment
2265 /// \param order the ByteOrder of the data
2266 /// \param result the word in the specified byte order
2267 /// \param block the byte buffer to be processed
2268 /// \details GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates
2269 /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
2270 /// LITTLE_ENDIAN_ORDER.
2271 /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w</tt>
2272 /// will be <tt>0x03020100</tt>.
2273 /// <pre>
2274 /// word32 w;
2275 /// byte buffer[4] = {0,1,2,3};
2276 /// w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer);
2277 /// </pre>
2278 template <class T>
2279 inline void GetWord(bool assumeAligned, ByteOrder order, T &result, const byte *block)
2280 {
2281  result = GetWord<T>(assumeAligned, order, block);
2282 }
2283 
2284 /// \brief Access a block of memory
2285 /// \tparam T class or type
2286 /// \param assumeAligned flag indicating alignment
2287 /// \param order the ByteOrder of the data
2288 /// \param block the destination byte buffer
2289 /// \param value the word in the specified byte order
2290 /// \param xorBlock an optional byte buffer to xor
2291 /// \details PutWord() provides alternate write access to a block of memory. The flag assumeAligned indicates
2292 /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
2293 /// LITTLE_ENDIAN_ORDER.
2294 template <class T>
2295 inline void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock = NULLPTR)
2296 {
2297  CRYPTOPP_UNUSED(assumeAligned);
2298 #ifdef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
2299  *reinterpret_cast<T *>((void *)block) = ConditionalByteReverse(order, value) ^ (xorBlock ? *reinterpret_cast<const T *>((const void *)xorBlock) : 0);
2300 #else
2301  T t1, t2;
2302  t1 = ConditionalByteReverse(order, value);
2303  if (xorBlock) {memcpy(&t2, xorBlock, sizeof(T)); t1 ^= t2;}
2304  memcpy(block, &t1, sizeof(T));
2305 #endif
2306 }
2307 
2308 /// \brief Access a block of memory
2309 /// \tparam T class or type
2310 /// \tparam B enumeration indicating endianness
2311 /// \tparam A flag indicating alignment
2312 /// \details GetBlock() provides alternate read access to a block of memory. The enumeration B is
2313 /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
2314 /// Repeatedly applying operator() results in advancing in the block of memory.
2315 /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w1</tt>
2316 /// will be <tt>0x03020100</tt> and <tt>w1</tt> will be <tt>0x07060504</tt>.
2317 /// <pre>
2318 /// word32 w1, w2;
2319 /// byte buffer[8] = {0,1,2,3,4,5,6,7};
2320 /// GetBlock<word32, LittleEndian> block(buffer);
2321 /// block(w1)(w2);
2322 /// </pre>
2323 template <class T, class B, bool A=false>
2325 {
2326 public:
2327  /// \brief Construct a GetBlock
2328  /// \param block the memory block
2329  GetBlock(const void *block)
2330  : m_block((const byte *)block) {}
2331 
2332  /// \brief Access a block of memory
2333  /// \tparam U class or type
2334  /// \param x the value to read
2335  /// \returns pointer to the remainder of the block after reading x
2336  template <class U>
2338  {
2339  CRYPTOPP_COMPILE_ASSERT(sizeof(U) >= sizeof(T));
2340  x = GetWord<T>(A, B::ToEnum(), m_block);
2341  m_block += sizeof(T);
2342  return *this;
2343  }
2344 
2345 private:
2346  const byte *m_block;
2347 };
2348 
2349 /// \brief Access a block of memory
2350 /// \tparam T class or type
2351 /// \tparam B enumeration indicating endianness
2352 /// \tparam A flag indicating alignment
2353 /// \details PutBlock() provides alternate write access to a block of memory. The enumeration B is
2354 /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
2355 /// Repeatedly applying operator() results in advancing in the block of memory.
2356 /// \details An example of writing two word32 values from a block of memory is shown below. After the code
2357 /// executes, the byte buffer will be <tt>{0,1,2,3,4,5,6,7}</tt>.
2358 /// <pre>
2359 /// word32 w1=0x03020100, w2=0x07060504;
2360 /// byte buffer[8];
2361 /// PutBlock<word32, LittleEndian> block(NULLPTR, buffer);
2362 /// block(w1)(w2);
2363 /// </pre>
2364 template <class T, class B, bool A=false>
2366 {
2367 public:
2368  /// \brief Construct a PutBlock
2369  /// \param block the memory block
2370  /// \param xorBlock optional mask
2371  PutBlock(const void *xorBlock, void *block)
2372  : m_xorBlock((const byte *)xorBlock), m_block((byte *)block) {}
2373 
2374  /// \brief Access a block of memory
2375  /// \tparam U class or type
2376  /// \param x the value to write
2377  /// \returns pointer to the remainder of the block after writing x
2378  template <class U>
2380  {
2381  PutWord(A, B::ToEnum(), m_block, (T)x, m_xorBlock);
2382  m_block += sizeof(T);
2383  if (m_xorBlock)
2384  m_xorBlock += sizeof(T);
2385  return *this;
2386  }
2387 
2388 private:
2389  const byte *m_xorBlock;
2390  byte *m_block;
2391 };
2392 
2393 /// \brief Access a block of memory
2394 /// \tparam T class or type
2395 /// \tparam B enumeration indicating endianness
2396 /// \tparam GA flag indicating alignment for the Get operation
2397 /// \tparam PA flag indicating alignment for the Put operation
2398 /// \details GetBlock() provides alternate write access to a block of memory. The enumeration B is
2399 /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
2400 /// \sa GetBlock() and PutBlock().
2401 template <class T, class B, bool GA=false, bool PA=false>
2403 {
2404  // function needed because of C++ grammatical ambiguity between expression-statements and declarations
2405  static inline GetBlock<T, B, GA> Get(const void *block) {return GetBlock<T, B, GA>(block);}
2406  typedef PutBlock<T, B, PA> Put;
2407 };
2408 
2409 /// \brief Convert a word to a string
2410 /// \tparam T class or type
2411 /// \param value the word to convert
2412 /// \param order byte order
2413 /// \returns a string representing the value of the word
2414 template <class T>
2415 std::string WordToString(T value, ByteOrder order = BIG_ENDIAN_ORDER)
2416 {
2417  if (!NativeByteOrderIs(order))
2418  value = ByteReverse(value);
2419 
2420  return std::string((char *)&value, sizeof(value));
2421 }
2422 
2423 /// \brief Convert a string to a word
2424 /// \tparam T class or type
2425 /// \param str the string to convert
2426 /// \param order byte order
2427 /// \returns a word representing the value of the string
2428 template <class T>
2429 T StringToWord(const std::string &str, ByteOrder order = BIG_ENDIAN_ORDER)
2430 {
2431  T value = 0;
2432  memcpy_s(&value, sizeof(value), str.data(), UnsignedMin(str.size(), sizeof(value)));
2433  return NativeByteOrderIs(order) ? value : ByteReverse(value);
2434 }
2435 
2436 // ************** help remove warning on g++ ***************
2437 
2438 /// \brief Safely shift values when undefined behavior could occur
2439 /// \tparam overflow boolean flag indicating if overflow is present
2440 /// \details SafeShifter safely shifts values when undefined behavior could occur under C/C++ rules.
2441 /// The class behaves much like a saturating arithmetic class, clamping values rather than allowing
2442 /// the compiler to remove undefined behavior.
2443 /// \sa SafeShifter<true>, SafeShifter<false>
2444 template <bool overflow> struct SafeShifter;
2445 
2446 /// \brief Shifts a value in the presence of overflow
2447 /// \details the true template parameter indicates overflow would occur.
2448 /// In this case, SafeShifter clamps the value and returns 0.
2449 template<> struct SafeShifter<true>
2450 {
2451  /// \brief Right shifts a value that overflows
2452  /// \tparam T class or type
2453  /// \return 0
2454  /// \details Since <tt>overflow == true</tt>, the value 0 is always returned.
2455  /// \sa SafeLeftShift
2456  template <class T>
2457  static inline T RightShift(T value, unsigned int bits)
2458  {
2459  CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits);
2460  return 0;
2461  }
2462 
2463  /// \brief Left shifts a value that overflows
2464  /// \tparam T class or type
2465  /// \return 0
2466  /// \details Since <tt>overflow == true</tt>, the value 0 is always returned.
2467  /// \sa SafeRightShift
2468  template <class T>
2469  static inline T LeftShift(T value, unsigned int bits)
2470  {
2471  CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits);
2472  return 0;
2473  }
2474 };
2475 
2476 /// \brief Shifts a value in the absence of overflow
2477 /// \details the false template parameter indicates overflow would not occur.
2478 /// In this case, SafeShifter returns the shfted value.
2479 template<> struct SafeShifter<false>
2480 {
2481  /// \brief Right shifts a value that does not overflow
2482  /// \tparam T class or type
2483  /// \return the shifted value
2484  /// \details Since <tt>overflow == false</tt>, the shifted value is returned.
2485  /// \sa SafeLeftShift
2486  template <class T>
2487  static inline T RightShift(T value, unsigned int bits)
2488  {
2489  return value >> bits;
2490  }
2491 
2492  /// \brief Left shifts a value that does not overflow
2493  /// \tparam T class or type
2494  /// \return the shifted value
2495  /// \details Since <tt>overflow == false</tt>, the shifted value is returned.
2496  /// \sa SafeRightShift
2497  template <class T>
2498  static inline T LeftShift(T value, unsigned int bits)
2499  {
2500  return value << bits;
2501  }
2502 };
2503 
2504 /// \brief Safely right shift values when undefined behavior could occur
2505 /// \tparam bits the number of bit positions to shift the value
2506 /// \tparam T class or type
2507 /// \param value the value to right shift
2508 /// \result the shifted value or 0
2509 /// \details SafeRightShift safely shifts the value to the right when undefined behavior
2510 /// could occur under C/C++ rules. SafeRightShift will return the shifted value or 0
2511 /// if undefined behavior would occur.
2512 template <unsigned int bits, class T>
2513 inline T SafeRightShift(T value)
2514 {
2515  return SafeShifter<(bits>=(8*sizeof(T)))>::RightShift(value, bits);
2516 }
2517 
2518 /// \brief Safely left shift values when undefined behavior could occur
2519 /// \tparam bits the number of bit positions to shift the value
2520 /// \tparam T class or type
2521 /// \param value the value to left shift
2522 /// \result the shifted value or 0
2523 /// \details SafeLeftShift safely shifts the value to the left when undefined behavior
2524 /// could occur under C/C++ rules. SafeLeftShift will return the shifted value or 0
2525 /// if undefined behavior would occur.
2526 template <unsigned int bits, class T>
2527 inline T SafeLeftShift(T value)
2528 {
2529  return SafeShifter<(bits>=(8*sizeof(T)))>::LeftShift(value, bits);
2530 }
2531 
2532 /// \brief Finds first element not in a range
2533 /// \tparam InputIt Input iterator type
2534 /// \tparam T class or type
2535 /// \param first iterator to first element
2536 /// \param last iterator to last element
2537 /// \param value the value used as a predicate
2538 /// \returns iterator to the first element in the range that is not value
2539 template<typename InputIt, typename T>
2540 inline InputIt FindIfNot(InputIt first, InputIt last, const T &value) {
2541 #ifdef CRYPTOPP_CXX11_LAMBDA
2542  return std::find_if(first, last, [&value](const T &o) {
2543  return value!=o;
2544  });
2545 #else
2546  return std::find_if(first, last, std::bind2nd(std::not_equal_to<T>(), value));
2547 #endif
2548 }
2549 
2550 // ************** use one buffer for multiple data members ***************
2551 
2552 #define CRYPTOPP_BLOCK_1(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+0);} size_t SS1() {return sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2553 #define CRYPTOPP_BLOCK_2(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS1());} size_t SS2() {return SS1()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2554 #define CRYPTOPP_BLOCK_3(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS2());} size_t SS3() {return SS2()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2555 #define CRYPTOPP_BLOCK_4(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS3());} size_t SS4() {return SS3()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2556 #define CRYPTOPP_BLOCK_5(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS4());} size_t SS5() {return SS4()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2557 #define CRYPTOPP_BLOCK_6(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS5());} size_t SS6() {return SS5()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2558 #define CRYPTOPP_BLOCK_7(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS6());} size_t SS7() {return SS6()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2559 #define CRYPTOPP_BLOCK_8(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS7());} size_t SS8() {return SS7()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
2560 #define CRYPTOPP_BLOCKS_END(i) size_t SST() {return SS##i();} void AllocateBlocks() {m_aggregate.New(SST());} AlignedSecByteBlock m_aggregate;
2561 
2562 NAMESPACE_END
2563 
2564 #if (CRYPTOPP_MSC_VERSION)
2565 # pragma warning(pop)
2566 #endif
2567 
2568 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
2569 # pragma GCC diagnostic pop
2570 #endif
2571 
2572 #endif
void SecureWipeBuffer(T *buf, size_t n)
Sets each element of an array to 0.
Definition: misc.h:1167
InputIt FindIfNot(InputIt first, InputIt last, const T &value)
Finds first element not in a range.
Definition: misc.h:2540
the cipher is performing decryption
Definition: cryptlib.h:124
An invalid argument was detected.
Definition: cryptlib.h:199
std::string StringNarrow(const wchar_t *str, bool throwOnError=true)
Converts a wide character C-string to a multibyte string.
Definition: misc.cpp:140
bool NativeByteOrderIs(ByteOrder order)
Determines whether order follows native byte ordering.
Definition: misc.h:1071
void memmove_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
Bounds checking replacement for memmove()
Definition: misc.h:428
bool SafeConvert(T1 from, T2 &to)
Tests whether a conversion from -> to is safe to perform.
Definition: misc.h:562
ByteOrder
Provides the byte ordering.
Definition: cryptlib.h:140
void AlignedDeallocate(void *ptr)
Frees a buffer allocated with AlignedAllocate.
Restricts the instantiation of a class to one static object without locks.
Definition: misc.h:291
void IncrementCounterByOne(byte *inout, unsigned int size)
Performs an addition with carry on a block of bytes.
Definition: misc.h:1108
T2 ModPowerOf2(const T1 &a, const T2 &b)
Reduces a value to a power of 2.
Definition: misc.h:922
T SafeRightShift(T value)
Safely right shift values when undefined behavior could occur.
Definition: misc.h:2513
size_t BitsToBytes(size_t bitCount)
Returns the number of 8-bit bytes or octets required for the specified number of bits.
Definition: misc.h:790
T StringToWord(const std::string &str, ByteOrder order=BIG_ENDIAN_ORDER)
Convert a string to a word.
Definition: misc.h:2429
bool IsAligned(const void *ptr)
Determines whether ptr is minimally aligned.
Definition: misc.h:1041
T rotlFixed(T x, unsigned int y)
Performs a left rotate.
Definition: misc.h:1416
size_t BitsToWords(size_t bitCount)
Returns the number of words required for the specified number of bits.
Definition: misc.h:810
void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock=NULL)
Access a block of memory.
Definition: misc.h:2295
unsigned int BytePrecision(const T &value)
Returns the number of 8-bit bytes or octets required for a value.
Definition: misc.h:671
PutBlock(const void *xorBlock, void *block)
Construct a PutBlock.
Definition: misc.h:2371
Converts an enumeration to a type suitable for use as a template parameter.
Definition: cryptlib.h:132
CipherDir
Specifies a direction for a cipher to operate.
Definition: cryptlib.h:120
Abstract base classes that provide a uniform interface to this library.
void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
Bounds checking replacement for memcpy()
Definition: misc.h:383
unsigned int GetAlignmentOf()
Returns the minimum alignment requirements of a type.
Definition: misc.h:998
static T LeftShift(T value, unsigned int bits)
Left shifts a value that does not overflow.
Definition: misc.h:2498
An object factory function.
Definition: misc.h:241
Classes for automatic resource management.
Library configuration file.
size_t BytesToWords(size_t byteCount)
Returns the number of words required for the specified number of bytes.
Definition: misc.h:800
Common C++ header files.
std::string IntToString< word64 >(word64 value, unsigned int base)
Converts an unsigned value to a string.
Definition: integer.cpp:4722
std::string WordToString(T value, ByteOrder order=BIG_ENDIAN_ORDER)
Convert a word to a string.
Definition: misc.h:2415
T rotlVariable(T x, unsigned int y)
Performs a left rotate.
Definition: misc.h:1465
Access a block of memory.
Definition: misc.h:2402
byte BitReverse(byte value)
Reverses bits in a 8-bit value.
Definition: misc.h:1905
byte order is little-endian
Definition: cryptlib.h:142
the cipher is performing encryption
Definition: cryptlib.h:122
T GetWord(bool assumeAligned, ByteOrder order, const byte *block)
Access a block of memory.
Definition: misc.h:2250
void SecureWipeArray(T *buf, size_t n)
Sets each element of an array to 0.
Definition: misc.h:1275
bool IsAlignedOn(const void *ptr, unsigned int alignment)
Determines whether ptr is aligned to a minimum value.
Definition: misc.h:1030
Uses encapsulation to hide an object in derived classes.
Definition: misc.h:217
void * UnalignedAllocate(size_t size)
Allocates a buffer.
Definition: misc.cpp:325
Manages resources for a single object.
Definition: smartptr.h:18
unsigned int TrailingZeros(word32 v)
Determines the number of trailing 0-bits in a value.
Definition: misc.h:719
T rotlConstant(T x)
Performs a left rotate.
Definition: misc.h:1365
void CallNewHandler()
Attempts to reclaim unused memory.
Definition: misc.cpp:268
#define CRYPTOPP_COMPILE_ASSERT(expr)
Compile time assertion.
Definition: misc.h:144
T Crop(T value, size_t bits)
Truncates the value to the specified number of bits.
Definition: misc.h:778
T ConditionalByteReverse(ByteOrder order, T value)
Reverses bytes in a value depending upon endianness.
Definition: misc.h:1979
void ConditionalSwapPointers(bool c, T &a, T &b)
Performs a branchless swap of pointers a and b if condition c is true.
Definition: misc.h:1151
Multiple precision integer with arithmetic operations.
Definition: integer.h:49
T1 SaturatingSubtract(const T1 &a, const T2 &b)
Performs a saturating subtract clamped at 0.
Definition: misc.h:890
CipherDir GetCipherDir(const T &obj)
Returns the direction the cipher is being operated.
Definition: misc.h:1087
const T1 UnsignedMin(const T1 &a, const T2 &b)
Safe comparison of values that could be neagtive and incorrectly promoted.
Definition: misc.h:546
bool IsPowerOf2(const T &value)
Tests whether a value is a power of 2.
Definition: misc.h:859
static T RightShift(T value, unsigned int bits)
Right shifts a value that does not overflow.
Definition: misc.h:2487
#define MEMORY_BARRIER
A memory barrier.
Definition: misc.h:255
void * memset_z(void *ptr, int value, size_t num)
Memory block initializer and eraser that attempts to survive optimizations.
Definition: misc.h:490
unsigned int Parity(T value)
Returns the parity of a value.
Definition: misc.h:659
byte order is big-endian
Definition: cryptlib.h:144
const T & STDMIN(const T &a, const T &b)
Replacement function for std::min.
Definition: misc.h:507
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:60
std::wstring StringWiden(const char *str, bool throwOnError=true)
Converts a multibyte C-string to a wide character string.
Definition: misc.cpp:204
PutBlock< T, B, A > & operator()(U x)
Access a block of memory.
Definition: misc.h:2379
void ConditionalSwap(bool c, T &a, T &b)
Performs a branchless swap of values a and b if condition c is true.
Definition: misc.h:1138
T1 SaturatingSubtract1(const T1 &a, const T2 &b)
Performs a saturating subtract clamped at 1.
Definition: misc.h:907
GetBlock(const void *block)
Construct a GetBlock.
Definition: misc.h:2329
T SafeLeftShift(T value)
Safely left shift values when undefined behavior could occur.
Definition: misc.h:2527
static T RightShift(T value, unsigned int bits)
Right shifts a value that overflows.
Definition: misc.h:2457
void xorbuf(byte *buf, const byte *mask, size_t count)
Performs an XOR of a buffer with a mask.
Definition: misc.cpp:32
T rotrConstant(T x)
Performs a right rotate.
Definition: misc.h:1391
Access a block of memory.
Definition: misc.h:2324
std::string IntToString(T value, unsigned int base=10)
Converts a value to a string.
Definition: misc.h:576
GetBlock< T, B, A > & operator()(U &x)
Access a block of memory.
Definition: misc.h:2337
bool VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count)
Performs a near constant-time comparison of two equally sized buffers.
Definition: misc.cpp:100
An Empty class.
Definition: misc.h:197
ByteOrder GetNativeByteOrder()
Returns NativeByteOrder as an enumerated ByteOrder value.
Definition: misc.h:1063
T1 RoundUpToMultipleOf(const T1 &n, const T2 &m)
Rounds a value up to a multiple of a second value.
Definition: misc.h:971
Safely shift values when undefined behavior could occur.
Definition: misc.h:2444
const T & STDMAX(const T &a, const T &b)
Replacement function for std::max.
Definition: misc.h:518
Access a block of memory.
Definition: misc.h:2365
std::string IntToString< Integer >(Integer value, unsigned int base)
Converts an Integer to a string.
Definition: integer.cpp:4656
Crypto++ library namespace.
T rotrVariable(T x, unsigned int y)
Performs a right rotate.
Definition: misc.h:1485
T rotlMod(T x, unsigned int y)
Performs a left rotate.
Definition: misc.h:1502
unsigned int GetByte(ByteOrder order, T value, unsigned int index)
Gets a byte from a value.
Definition: misc.h:1827
T rotrMod(T x, unsigned int y)
Performs a right rotate.
Definition: misc.h:1518
T rotrFixed(T x, unsigned int y)
Performs a right rotate.
Definition: misc.h:1441
Ensures an object is not copyable.
Definition: misc.h:228
byte ByteReverse(byte value)
Reverses bytes in a 8-bit value.
Definition: misc.h:1838
void UnalignedDeallocate(void *ptr)
Frees a buffer allocated with UnalignedAllocate.
Definition: misc.cpp:333
unsigned int BitPrecision(const T &value)
Returns the number of bits required for a value.
Definition: misc.h:694
const T & Ref(...) const
Return a reference to the inner Singleton object.
Definition: misc.h:312
size_t BitsToDwords(size_t bitCount)
Returns the number of double words required for the specified number of bits.
Definition: misc.h:820
static T LeftShift(T value, unsigned int bits)
Left shifts a value that overflows.
Definition: misc.h:2469
T1 RoundDownToMultipleOf(const T1 &n, const T2 &m)
Rounds a value down to a multiple of a second value.
Definition: misc.h:941
void * AlignedAllocate(size_t size)
Allocates a buffer on 16-byte boundary.
void vec_swap(T &a, T &b)
Swaps two variables which are arrays.
Definition: misc.h:471