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