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 defined(CRYPTOPP_LITTLE_ENDIAN)
1098  typedef LittleEndian NativeByteOrder;
1099 #elif defined(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 attempts to survive optimizations and dead code removal
1217 template <class T>
1218 void SecureWipeBuffer(T *buf, size_t n)
1219 {
1220  // GCC 4.3.2 on Cygwin optimizes away the first store if this loop is done in the forward direction
1221  volatile T *p = buf+n;
1222  while (n--)
1223  *(--p) = 0;
1224 }
1225 
1226 #if (_MSC_VER >= 1400 || defined(__GNUC__)) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86)
1227 
1228 /// \brief Sets each byte of an array to 0
1229 /// \param buf an array of bytes
1230 /// \param n the number of elements in the array
1231 /// \details The operation performs a wipe or zeroization. The function attempts to survive optimizations and dead code removal.
1232 template<> inline void SecureWipeBuffer(byte *buf, size_t n)
1233 {
1234  volatile byte *p = buf;
1235 #ifdef __GNUC__
1236  asm volatile("rep stosb" : "+c"(n), "+D"(p) : "a"(0) : "memory");
1237 #else
1238  __stosb(reinterpret_cast<byte *>(reinterpret_cast<size_t>(p)), 0, n);
1239 #endif
1240 }
1241 
1242 /// \brief Sets each 16-bit element of an array to 0
1243 /// \param buf an array of 16-bit words
1244 /// \param n the number of elements in the array
1245 /// \details The operation performs a wipe or zeroization. The function attempts to survive optimizations and dead code removal.
1246 template<> inline void SecureWipeBuffer(word16 *buf, size_t n)
1247 {
1248  volatile word16 *p = buf;
1249 #ifdef __GNUC__
1250  asm volatile("rep stosw" : "+c"(n), "+D"(p) : "a"(0) : "memory");
1251 #else
1252  __stosw(reinterpret_cast<word16 *>(reinterpret_cast<size_t>(p)), 0, n);
1253 #endif
1254 }
1255 
1256 /// \brief Sets each 32-bit element of an array to 0
1257 /// \param buf an array of 32-bit words
1258 /// \param n the number of elements in the array
1259 /// \details The operation performs a wipe or zeroization. The function attempts to survive optimizations and dead code removal.
1260 template<> inline void SecureWipeBuffer(word32 *buf, size_t n)
1261 {
1262  volatile word32 *p = buf;
1263 #ifdef __GNUC__
1264  asm volatile("rep stosl" : "+c"(n), "+D"(p) : "a"(0) : "memory");
1265 #else
1266  __stosd(reinterpret_cast<unsigned long *>(reinterpret_cast<size_t>(p)), 0, n);
1267 #endif
1268 }
1269 
1270 /// \brief Sets each 64-bit element of an array to 0
1271 /// \param buf an array of 64-bit words
1272 /// \param n the number of elements in the array
1273 /// \details The operation performs a wipe or zeroization. The function attempts to survive optimizations and dead code removal.
1274 template<> inline void SecureWipeBuffer(word64 *buf, size_t n)
1275 {
1276 #if CRYPTOPP_BOOL_X64
1277  volatile word64 *p = buf;
1278 #ifdef __GNUC__
1279  asm volatile("rep stosq" : "+c"(n), "+D"(p) : "a"(0) : "memory");
1280 #else
1281  __stosq(reinterpret_cast<word64 *>(reinterpret_cast<size_t>(p)), 0, n);
1282 #endif
1283 #else
1284  SecureWipeBuffer(reinterpret_cast<word32 *>(buf), 2*n);
1285 #endif
1286 }
1287 
1288 #endif // #if (_MSC_VER >= 1400 || defined(__GNUC__)) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86)
1289 
1290 #if (_MSC_VER >= 1700) && defined(_M_ARM)
1291 template<> inline void SecureWipeBuffer(byte *buf, size_t n)
1292 {
1293  char *p = reinterpret_cast<char*>(buf+n);
1294  while (n--)
1295  __iso_volatile_store8(--p, 0);
1296 }
1297 
1298 template<> inline void SecureWipeBuffer(word16 *buf, size_t n)
1299 {
1300  short *p = reinterpret_cast<short*>(buf+n);
1301  while (n--)
1302  __iso_volatile_store16(--p, 0);
1303 }
1304 
1305 template<> inline void SecureWipeBuffer(word32 *buf, size_t n)
1306 {
1307  int *p = reinterpret_cast<int*>(buf+n);
1308  while (n--)
1309  __iso_volatile_store32(--p, 0);
1310 }
1311 
1312 template<> inline void SecureWipeBuffer(word64 *buf, size_t n)
1313 {
1314  __int64 *p = reinterpret_cast<__int64*>(buf+n);
1315  while (n--)
1316  __iso_volatile_store64(--p, 0);
1317 }
1318 #endif
1319 
1320 /// \brief Sets each element of an array to 0
1321 /// \tparam T class or type
1322 /// \param buf an array of elements
1323 /// \param n the number of elements in the array
1324 /// \details The operation performs a wipe or zeroization. The function attempts to survive optimizations and dead code removal.
1325 template <class T>
1326 inline void SecureWipeArray(T *buf, size_t n)
1327 {
1328  if (sizeof(T) % 8 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word64>() == 0)
1329  SecureWipeBuffer(reinterpret_cast<word64 *>(static_cast<void *>(buf)), n * (sizeof(T)/8));
1330  else if (sizeof(T) % 4 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word32>() == 0)
1331  SecureWipeBuffer(reinterpret_cast<word32 *>(static_cast<void *>(buf)), n * (sizeof(T)/4));
1332  else if (sizeof(T) % 2 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word16>() == 0)
1333  SecureWipeBuffer(reinterpret_cast<word16 *>(static_cast<void *>(buf)), n * (sizeof(T)/2));
1334  else
1335  SecureWipeBuffer(reinterpret_cast<byte *>(static_cast<void *>(buf)), n * sizeof(T));
1336 }
1337 
1338 /// \brief Converts a wide character C-string to a multibyte string
1339 /// \param str C-string consisting of wide characters
1340 /// \param throwOnError flag indicating the function should throw on error
1341 /// \returns str converted to a multibyte string or an empty string.
1342 /// \details StringNarrow() converts a wide string to a narrow string using C++ std::wcstombs() under
1343 /// the executing thread's locale. A locale must be set before using this function, and it can be
1344 /// set with std::setlocale() if needed. Upon success, the converted string is returned.
1345 /// \details Upon failure with throwOnError as false, the function returns an empty string. If
1346 /// throwOnError as true, the function throws an InvalidArgument() exception.
1347 /// \note If you try to convert, say, the Chinese character for "bone" from UTF-16 (0x9AA8) to UTF-8
1348 /// (0xE9 0xAA 0xA8), then you must ensure the locale is available. If the locale is not available,
1349 /// then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception.
1350 std::string StringNarrow(const wchar_t *str, bool throwOnError = true);
1351 
1352 /// \brief Converts a multibyte C-string to a wide character string
1353 /// \param str C-string consisting of wide characters
1354 /// \param throwOnError flag indicating the function should throw on error
1355 /// \returns str converted to a multibyte string or an empty string.
1356 /// \details StringWiden() converts a narrow string to a wide string using C++ std::mbstowcs() under
1357 /// the executing thread's locale. A locale must be set before using this function, and it can be
1358 /// set with std::setlocale() if needed. Upon success, the converted string is returned.
1359 /// \details Upon failure with throwOnError as false, the function returns an empty string. If
1360 /// throwOnError as true, the function throws an InvalidArgument() exception.
1361 /// \note If you try to convert, say, the Chinese character for "bone" from UTF-8 (0xE9 0xAA 0xA8)
1362 /// to UTF-16 (0x9AA8), then you must ensure the locale is available. If the locale is not available,
1363 /// then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception.
1364 std::wstring StringWiden(const char *str, bool throwOnError = true);
1365 
1366 #ifdef CRYPTOPP_DOXYGEN_PROCESSING
1367 
1368 /// \brief Allocates a buffer on 16-byte boundary
1369 /// \param size the size of the buffer
1370 /// \details AlignedAllocate is primarily used when the data will be proccessed by MMX, SSE2 and NEON
1371 /// instructions. The assembly language routines rely on the alignment. If the alignment is not
1372 /// respected, then a SIGBUS could be generated on Unix and Linux, and an
1373 /// EXCEPTION_DATATYPE_MISALIGNMENT could be generated on Windows.
1374 /// \note AlignedAllocate and AlignedDeallocate are available when CRYPTOPP_BOOL_ALIGN16 is
1375 /// defined. CRYPTOPP_BOOL_ALIGN16 is defined in config.h
1376 CRYPTOPP_DLL void* CRYPTOPP_API AlignedAllocate(size_t size);
1377 
1378 /// \brief Frees a buffer allocated with AlignedAllocate
1379 /// \param ptr the buffer to free
1380 /// \note AlignedAllocate and AlignedDeallocate are available when CRYPTOPP_BOOL_ALIGN16 is
1381 /// defined. CRYPTOPP_BOOL_ALIGN16 is defined in config.h
1382 CRYPTOPP_DLL void CRYPTOPP_API AlignedDeallocate(void *ptr);
1383 
1384 #endif // CRYPTOPP_DOXYGEN_PROCESSING
1385 
1386 #if CRYPTOPP_BOOL_ALIGN16
1387 CRYPTOPP_DLL void* CRYPTOPP_API AlignedAllocate(size_t size);
1388 CRYPTOPP_DLL void CRYPTOPP_API AlignedDeallocate(void *ptr);
1389 #endif // CRYPTOPP_BOOL_ALIGN16
1390 
1391 /// \brief Allocates a buffer
1392 /// \param size the size of the buffer
1393 CRYPTOPP_DLL void * CRYPTOPP_API UnalignedAllocate(size_t size);
1394 
1395 /// \brief Frees a buffer allocated with UnalignedAllocate
1396 /// \param ptr the buffer to free
1397 CRYPTOPP_DLL void CRYPTOPP_API UnalignedDeallocate(void *ptr);
1398 
1399 // ************** rotate functions ***************
1400 
1401 /// \brief Performs a left rotate
1402 /// \tparam R the number of bit positions to rotate the value
1403 /// \tparam T the word type
1404 /// \param x the value to rotate
1405 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1406 /// \details R must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1407 /// Use rotlMod if the rotate amount R is outside the range.
1408 /// \details Use rotlConstant when the rotate amount is constant. The template function was added
1409 /// because Clang did not propagate the constant when passed as a function parameter. Clang's
1410 /// need for a constexpr meant rotlFixed failed to compile on occassion.
1411 /// \note rotlConstant attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1412 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1413 /// counterparts.
1414 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1415 /// \since Crypto++ 6.0
1416 template <unsigned int R, class T> inline T rotlConstant(T x)
1417 {
1418  // Portable rotate that reduces to single instruction...
1419  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
1420  // http://software.intel.com/en-us/forums/topic/580884
1421  // and http://llvm.org/bugs/show_bug.cgi?id=24226
1422  static const unsigned int THIS_SIZE = sizeof(T)*8;
1423  static const unsigned int MASK = THIS_SIZE-1;
1424  CRYPTOPP_ASSERT(R < THIS_SIZE);
1425  return T((x<<R)|(x>>(-R&MASK)));
1426 }
1427 
1428 /// \brief Performs a right rotate
1429 /// \tparam R the number of bit positions to rotate the value
1430 /// \tparam T the word type
1431 /// \param x the value to rotate
1432 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1433 /// \details R must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1434 /// Use rotrMod if the rotate amount R is outside the range.
1435 /// \details Use rotrConstant when the rotate amount is constant. The template function was added
1436 /// because Clang did not propagate the constant when passed as a function parameter. Clang's
1437 /// need for a constexpr meant rotrFixed failed to compile on occassion.
1438 /// \note rotrConstant attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1439 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1440 /// counterparts.
1441 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1442 template <unsigned int R, class T> inline T rotrConstant(T x)
1443 {
1444  // Portable rotate that reduces to single instruction...
1445  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
1446  // http://software.intel.com/en-us/forums/topic/580884
1447  // and http://llvm.org/bugs/show_bug.cgi?id=24226
1448  static const unsigned int THIS_SIZE = sizeof(T)*8;
1449  static const unsigned int MASK = THIS_SIZE-1;
1450  CRYPTOPP_ASSERT(R < THIS_SIZE);
1451  return T((x >> R)|(x<<(-R&MASK)));
1452 }
1453 
1454 /// \brief Performs a left rotate
1455 /// \tparam T the word type
1456 /// \param x the value to rotate
1457 /// \param y the number of bit positions to rotate the value
1458 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1459 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1460 /// Use rotlMod if the rotate amount y is outside the range.
1461 /// \note rotlFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1462 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1463 /// counterparts. New code should use <tt>rotlConstant</tt>, which accepts the rotate amount as a
1464 /// template parameter.
1465 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1466 /// \since Crypto++ 6.0
1467 template <class T> inline T rotlFixed(T x, unsigned int y)
1468 {
1469  // Portable rotate that reduces to single instruction...
1470  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
1471  // http://software.intel.com/en-us/forums/topic/580884
1472  // and http://llvm.org/bugs/show_bug.cgi?id=24226
1473  static const unsigned int THIS_SIZE = sizeof(T)*8;
1474  static const unsigned int MASK = THIS_SIZE-1;
1475  CRYPTOPP_ASSERT(y < THIS_SIZE);
1476  return T((x<<y)|(x>>(-y&MASK)));
1477 }
1478 
1479 /// \brief Performs a right rotate
1480 /// \tparam T the word type
1481 /// \param x the value to rotate
1482 /// \param y the number of bit positions to rotate the value
1483 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1484 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1485 /// Use rotrMod if the rotate amount y is outside the range.
1486 /// \note rotrFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1487 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1488 /// counterparts. New code should use <tt>rotrConstant</tt>, which accepts the rotate amount as a
1489 /// template parameter.
1490 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1491 /// \since Crypto++ 3.0
1492 template <class T> inline T rotrFixed(T x, unsigned int y)
1493 {
1494  // Portable rotate that reduces to single instruction...
1495  // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
1496  // http://software.intel.com/en-us/forums/topic/580884
1497  // and http://llvm.org/bugs/show_bug.cgi?id=24226
1498  static const unsigned int THIS_SIZE = sizeof(T)*8;
1499  static const unsigned int MASK = THIS_SIZE-1;
1500  CRYPTOPP_ASSERT(y < THIS_SIZE);
1501  return T((x >> y)|(x<<(-y&MASK)));
1502 }
1503 
1504 /// \brief Performs a left rotate
1505 /// \tparam T the word type
1506 /// \param x the value to rotate
1507 /// \param y the number of bit positions to rotate the value
1508 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1509 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1510 /// Use rotlMod if the rotate amount y is outside the range.
1511 /// \note rotlVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1512 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1513 /// counterparts.
1514 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1515 /// \since Crypto++ 3.0
1516 template <class T> inline T rotlVariable(T x, unsigned int y)
1517 {
1518  static const unsigned int THIS_SIZE = sizeof(T)*8;
1519  static const unsigned int MASK = THIS_SIZE-1;
1520  CRYPTOPP_ASSERT(y < THIS_SIZE);
1521  return T((x<<y)|(x>>(-y&MASK)));
1522 }
1523 
1524 /// \brief Performs a right rotate
1525 /// \tparam T the word type
1526 /// \param x the value to rotate
1527 /// \param y the number of bit positions to rotate the value
1528 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1529 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1530 /// Use rotrMod if the rotate amount y is outside the range.
1531 /// \note rotrVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
1532 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
1533 /// counterparts.
1534 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1535 /// \since Crypto++ 3.0
1536 template <class T> inline T rotrVariable(T x, unsigned int y)
1537 {
1538  static const unsigned int THIS_SIZE = sizeof(T)*8;
1539  static const unsigned int MASK = THIS_SIZE-1;
1540  CRYPTOPP_ASSERT(y < THIS_SIZE);
1541  return T((x>>y)|(x<<(-y&MASK)));
1542 }
1543 
1544 /// \brief Performs a left rotate
1545 /// \tparam T the word type
1546 /// \param x the value to rotate
1547 /// \param y the number of bit positions to rotate the value
1548 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1549 /// \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1550 /// \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>.
1551 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1552 /// \since Crypto++ 3.0
1553 template <class T> inline T rotlMod(T x, unsigned int y)
1554 {
1555  static const unsigned int THIS_SIZE = sizeof(T)*8;
1556  static const unsigned int MASK = THIS_SIZE-1;
1557  return T((x<<(y&MASK))|(x>>(-y&MASK)));
1558 }
1559 
1560 /// \brief Performs a right rotate
1561 /// \tparam T the word type
1562 /// \param x the value to rotate
1563 /// \param y the number of bit positions to rotate the value
1564 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
1565 /// \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1566 /// \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>.
1567 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
1568 /// \since Crypto++ 3.0
1569 template <class T> inline T rotrMod(T x, unsigned int y)
1570 {
1571  static const unsigned int THIS_SIZE = sizeof(T)*8;
1572  static const unsigned int MASK = THIS_SIZE-1;
1573  return T((x>>(y&MASK))|(x<<(-y&MASK)));
1574 }
1575 
1576 #ifdef _MSC_VER
1577 
1578 /// \brief Performs a left rotate
1579 /// \tparam T the word type
1580 /// \param x the 32-bit value to rotate
1581 /// \param y the number of bit positions to rotate the value
1582 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1583 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1584 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1585 /// \note rotlFixed will assert in Debug builds if is outside the allowed range.
1586 /// \since Crypto++ 3.0
1587 template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y)
1588 {
1589  // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
1590  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1591  return y ? _lrotl(x, static_cast<byte>(y)) : x;
1592 }
1593 
1594 /// \brief Performs a right rotate
1595 /// \tparam T the word type
1596 /// \param x the 32-bit value to rotate
1597 /// \param y the number of bit positions to rotate the value
1598 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1599 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1600 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1601 /// \note rotrFixed will assert in Debug builds if is outside the allowed range.
1602 /// \since Crypto++ 3.0
1603 template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y)
1604 {
1605  // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
1606  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1607  return y ? _lrotr(x, static_cast<byte>(y)) : x;
1608 }
1609 
1610 /// \brief Performs a left rotate
1611 /// \tparam T the word type
1612 /// \param x the 32-bit value to rotate
1613 /// \param y the number of bit positions to rotate the value
1614 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1615 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1616 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1617 /// \note rotlVariable will assert in Debug builds if is outside the allowed range.
1618 /// \since Crypto++ 3.0
1619 template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y)
1620 {
1621  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1622  return _lrotl(x, static_cast<byte>(y));
1623 }
1624 
1625 /// \brief Performs a right rotate
1626 /// \tparam T the word type
1627 /// \param x the 32-bit value to rotate
1628 /// \param y the number of bit positions to rotate the value
1629 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1630 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1631 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1632 /// \note rotrVariable will assert in Debug builds if is outside the allowed range.
1633 /// \since Crypto++ 3.0
1634 template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y)
1635 {
1636  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1637  return _lrotr(x, static_cast<byte>(y));
1638 }
1639 
1640 /// \brief Performs a left rotate
1641 /// \tparam T the word type
1642 /// \param x the 32-bit value to rotate
1643 /// \param y the number of bit positions to rotate the value
1644 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1645 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1646 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1647 /// \since Crypto++ 3.0
1648 template<> inline word32 rotlMod<word32>(word32 x, unsigned int y)
1649 {
1650  y %= 8*sizeof(x);
1651  return _lrotl(x, static_cast<byte>(y));
1652 }
1653 
1654 /// \brief Performs a right rotate
1655 /// \tparam T the word type
1656 /// \param x the 32-bit value to rotate
1657 /// \param y the number of bit positions to rotate the value
1658 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1659 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
1660 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1661 /// \since Crypto++ 3.0
1662 template<> inline word32 rotrMod<word32>(word32 x, unsigned int y)
1663 {
1664  y %= 8*sizeof(x);
1665  return _lrotr(x, static_cast<byte>(y));
1666 }
1667 
1668 #endif // #ifdef _MSC_VER
1669 
1670 #if (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
1671 // Intel C++ Compiler 10.0 calls a function instead of using the rotate instruction when using these instructions
1672 
1673 /// \brief Performs a left rotate
1674 /// \tparam T the word type
1675 /// \param x the 64-bit value to rotate
1676 /// \param y the number of bit positions to rotate the value
1677 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1678 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1679 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1680 /// \note rotrFixed will assert in Debug builds if is outside the allowed range.
1681 /// \since Crypto++ 3.0
1682 template<> inline word64 rotlFixed<word64>(word64 x, unsigned int y)
1683 {
1684  // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
1685  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1686  return y ? _rotl64(x, static_cast<byte>(y)) : x;
1687 }
1688 
1689 /// \brief Performs a right rotate
1690 /// \tparam T the word type
1691 /// \param x the 64-bit value to rotate
1692 /// \param y the number of bit positions to rotate the value
1693 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1694 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1695 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1696 /// \note rotrFixed will assert in Debug builds if is outside the allowed range.
1697 /// \since Crypto++ 3.0
1698 template<> inline word64 rotrFixed<word64>(word64 x, unsigned int y)
1699 {
1700  // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
1701  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1702  return y ? _rotr64(x, static_cast<byte>(y)) : x;
1703 }
1704 
1705 /// \brief Performs a left rotate
1706 /// \tparam T the word type
1707 /// \param x the 64-bit value to rotate
1708 /// \param y the number of bit positions to rotate the value
1709 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1710 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1711 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1712 /// \note rotlVariable will assert in Debug builds if is outside the allowed range.
1713 /// \since Crypto++ 3.0
1714 template<> inline word64 rotlVariable<word64>(word64 x, unsigned int y)
1715 {
1716  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1717  return _rotl64(x, static_cast<byte>(y));
1718 }
1719 
1720 /// \brief Performs a right rotate
1721 /// \tparam T the word type
1722 /// \param x the 64-bit value to rotate
1723 /// \param y the number of bit positions to rotate the value
1724 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1725 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1726 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1727 /// \note rotrVariable will assert in Debug builds if is outside the allowed range.
1728 /// \since Crypto++ 3.0
1729 template<> inline word64 rotrVariable<word64>(word64 x, unsigned int y)
1730 {
1731  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1732  return y ? _rotr64(x, static_cast<byte>(y)) : x;
1733 }
1734 
1735 /// \brief Performs a left rotate
1736 /// \tparam T the word type
1737 /// \param x the 64-bit value to rotate
1738 /// \param y the number of bit positions to rotate the value
1739 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
1740 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1741 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1742 /// \since Crypto++ 3.0
1743 template<> inline word64 rotlMod<word64>(word64 x, unsigned int y)
1744 {
1745  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1746  return y ? _rotl64(x, static_cast<byte>(y)) : x;
1747 }
1748 
1749 /// \brief Performs a right rotate
1750 /// \tparam T the word type
1751 /// \param x the 64-bit value to rotate
1752 /// \param y the number of bit positions to rotate the value
1753 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
1754 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
1755 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
1756 /// \since Crypto++ 3.0
1757 template<> inline word64 rotrMod<word64>(word64 x, unsigned int y)
1758 {
1759  CRYPTOPP_ASSERT(y < 8*sizeof(x));
1760  return y ? _rotr64(x, static_cast<byte>(y)) : x;
1761 }
1762 
1763 #endif // #if _MSC_VER >= 1310
1764 
1765 #if _MSC_VER >= 1400 && !defined(__INTEL_COMPILER)
1766 // Intel C++ Compiler 10.0 gives undefined externals with these
1767 template<> inline word16 rotlFixed<word16>(word16 x, unsigned int y)
1768 {
1769  // Intrinsic, not bound to C/C++ language rules.
1770  return _rotl16(x, static_cast<byte>(y));
1771 }
1772 
1773 template<> inline word16 rotrFixed<word16>(word16 x, unsigned int y)
1774 {
1775  // Intrinsic, not bound to C/C++ language rules.
1776  return _rotr16(x, static_cast<byte>(y));
1777 }
1778 
1779 template<> inline word16 rotlVariable<word16>(word16 x, unsigned int y)
1780 {
1781  return _rotl16(x, static_cast<byte>(y));
1782 }
1783 
1784 template<> inline word16 rotrVariable<word16>(word16 x, unsigned int y)
1785 {
1786  return _rotr16(x, static_cast<byte>(y));
1787 }
1788 
1789 template<> inline word16 rotlMod<word16>(word16 x, unsigned int y)
1790 {
1791  return _rotl16(x, static_cast<byte>(y));
1792 }
1793 
1794 template<> inline word16 rotrMod<word16>(word16 x, unsigned int y)
1795 {
1796  return _rotr16(x, static_cast<byte>(y));
1797 }
1798 
1799 template<> inline byte rotlFixed<byte>(byte x, unsigned int y)
1800 {
1801  // Intrinsic, not bound to C/C++ language rules.
1802  return _rotl8(x, static_cast<byte>(y));
1803 }
1804 
1805 template<> inline byte rotrFixed<byte>(byte x, unsigned int y)
1806 {
1807  // Intrinsic, not bound to C/C++ language rules.
1808  return _rotr8(x, static_cast<byte>(y));
1809 }
1810 
1811 template<> inline byte rotlVariable<byte>(byte x, unsigned int y)
1812 {
1813  return _rotl8(x, static_cast<byte>(y));
1814 }
1815 
1816 template<> inline byte rotrVariable<byte>(byte x, unsigned int y)
1817 {
1818  return _rotr8(x, static_cast<byte>(y));
1819 }
1820 
1821 template<> inline byte rotlMod<byte>(byte x, unsigned int y)
1822 {
1823  return _rotl8(x, static_cast<byte>(y));
1824 }
1825 
1826 template<> inline byte rotrMod<byte>(byte x, unsigned int y)
1827 {
1828  return _rotr8(x, static_cast<byte>(y));
1829 }
1830 
1831 #endif // #if _MSC_VER >= 1400
1832 
1833 #if (defined(__MWERKS__) && TARGET_CPU_PPC)
1834 
1835 template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y)
1836 {
1837  CRYPTOPP_ASSERT(y < 32);
1838  return y ? __rlwinm(x,y,0,31) : x;
1839 }
1840 
1841 template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y)
1842 {
1843  CRYPTOPP_ASSERT(y < 32);
1844  return y ? __rlwinm(x,32-y,0,31) : x;
1845 }
1846 
1847 template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y)
1848 {
1849  CRYPTOPP_ASSERT(y < 32);
1850  return (__rlwnm(x,y,0,31));
1851 }
1852 
1853 template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y)
1854 {
1855  CRYPTOPP_ASSERT(y < 32);
1856  return (__rlwnm(x,32-y,0,31));
1857 }
1858 
1859 template<> inline word32 rotlMod<word32>(word32 x, unsigned int y)
1860 {
1861  return (__rlwnm(x,y,0,31));
1862 }
1863 
1864 template<> inline word32 rotrMod<word32>(word32 x, unsigned int y)
1865 {
1866  return (__rlwnm(x,32-y,0,31));
1867 }
1868 
1869 #endif // #if (defined(__MWERKS__) && TARGET_CPU_PPC)
1870 
1871 // ************** endian reversal ***************
1872 
1873 /// \brief Gets a byte from a value
1874 /// \param order the ByteOrder of the value
1875 /// \param value the value to retrieve the byte
1876 /// \param index the location of the byte to retrieve
1877 template <class T>
1878 inline unsigned int GetByte(ByteOrder order, T value, unsigned int index)
1879 {
1880  if (order == LITTLE_ENDIAN_ORDER)
1881  return GETBYTE(value, index);
1882  else
1883  return GETBYTE(value, sizeof(T)-index-1);
1884 }
1885 
1886 /// \brief Reverses bytes in a 8-bit value
1887 /// \param value the 8-bit value to reverse
1888 /// \note ByteReverse returns the value passed to it since there is nothing to reverse
1889 inline byte ByteReverse(byte value)
1890 {
1891  return value;
1892 }
1893 
1894 /// \brief Reverses bytes in a 16-bit value
1895 /// \param value the 16-bit value to reverse
1896 /// \details ByteReverse calls bswap if available. Otherwise the function performs a 8-bit rotate on the word16
1897 inline word16 ByteReverse(word16 value)
1898 {
1899 #if defined(CRYPTOPP_BYTESWAP_AVAILABLE)
1900  return bswap_16(value);
1901 #elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
1902  return _byteswap_ushort(value);
1903 #else
1904  return rotlFixed(value, 8U);
1905 #endif
1906 }
1907 
1908 /// \brief Reverses bytes in a 32-bit value
1909 /// \param value the 32-bit value to reverse
1910 /// \details ByteReverse calls bswap if available. Otherwise the function uses a combination of rotates on the word32
1911 inline word32 ByteReverse(word32 value)
1912 {
1913 #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
1914  __asm__ ("bswap %0" : "=r" (value) : "0" (value));
1915  return value;
1916 #elif defined(CRYPTOPP_BYTESWAP_AVAILABLE)
1917  return bswap_32(value);
1918 #elif defined(__MWERKS__) && TARGET_CPU_PPC
1919  return (word32)__lwbrx(&value,0);
1920 #elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
1921  return _byteswap_ulong(value);
1922 #elif CRYPTOPP_FAST_ROTATE(32) && !defined(__xlC__)
1923  // 5 instructions with rotate instruction, 9 without
1924  return (rotrFixed(value, 8U) & 0xff00ff00) | (rotlFixed(value, 8U) & 0x00ff00ff);
1925 #else
1926  // 6 instructions with rotate instruction, 8 without
1927  value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
1928  return rotlFixed(value, 16U);
1929 #endif
1930 }
1931 
1932 /// \brief Reverses bytes in a 64-bit value
1933 /// \param value the 64-bit value to reverse
1934 /// \details ByteReverse calls bswap if available. Otherwise the function uses a combination of rotates on the word64
1935 inline word64 ByteReverse(word64 value)
1936 {
1937 #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE) && defined(__x86_64__)
1938  __asm__ ("bswap %0" : "=r" (value) : "0" (value));
1939  return value;
1940 #elif defined(CRYPTOPP_BYTESWAP_AVAILABLE)
1941  return bswap_64(value);
1942 #elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
1943  return _byteswap_uint64(value);
1944 #elif CRYPTOPP_BOOL_SLOW_WORD64
1945  return (word64(ByteReverse(word32(value))) << 32) | ByteReverse(word32(value>>32));
1946 #else
1947  value = ((value & W64LIT(0xFF00FF00FF00FF00)) >> 8) | ((value & W64LIT(0x00FF00FF00FF00FF)) << 8);
1948  value = ((value & W64LIT(0xFFFF0000FFFF0000)) >> 16) | ((value & W64LIT(0x0000FFFF0000FFFF)) << 16);
1949  return rotlFixed(value, 32U);
1950 #endif
1951 }
1952 
1953 /// \brief Reverses bits in a 8-bit value
1954 /// \param value the 8-bit value to reverse
1955 /// \details BitReverse performs a combination of shifts on the byte
1956 inline byte BitReverse(byte value)
1957 {
1958  value = byte((value & 0xAA) >> 1) | byte((value & 0x55) << 1);
1959  value = byte((value & 0xCC) >> 2) | byte((value & 0x33) << 2);
1960  return rotlFixed(value, 4U);
1961 }
1962 
1963 /// \brief Reverses bits in a 16-bit value
1964 /// \param value the 16-bit value to reverse
1965 /// \details BitReverse performs a combination of shifts on the word16
1966 inline word16 BitReverse(word16 value)
1967 {
1968  value = word16((value & 0xAAAA) >> 1) | word16((value & 0x5555) << 1);
1969  value = word16((value & 0xCCCC) >> 2) | word16((value & 0x3333) << 2);
1970  value = word16((value & 0xF0F0) >> 4) | word16((value & 0x0F0F) << 4);
1971  return ByteReverse(value);
1972 }
1973 
1974 /// \brief Reverses bits in a 32-bit value
1975 /// \param value the 32-bit value to reverse
1976 /// \details BitReverse performs a combination of shifts on the word32
1977 inline word32 BitReverse(word32 value)
1978 {
1979  value = word32((value & 0xAAAAAAAA) >> 1) | word32((value & 0x55555555) << 1);
1980  value = word32((value & 0xCCCCCCCC) >> 2) | word32((value & 0x33333333) << 2);
1981  value = word32((value & 0xF0F0F0F0) >> 4) | word32((value & 0x0F0F0F0F) << 4);
1982  return ByteReverse(value);
1983 }
1984 
1985 /// \brief Reverses bits in a 64-bit value
1986 /// \param value the 64-bit value to reverse
1987 /// \details BitReverse performs a combination of shifts on the word64
1988 inline word64 BitReverse(word64 value)
1989 {
1990 #if CRYPTOPP_BOOL_SLOW_WORD64
1991  return (word64(BitReverse(word32(value))) << 32) | BitReverse(word32(value>>32));
1992 #else
1993  value = word64((value & W64LIT(0xAAAAAAAAAAAAAAAA)) >> 1) | word64((value & W64LIT(0x5555555555555555)) << 1);
1994  value = word64((value & W64LIT(0xCCCCCCCCCCCCCCCC)) >> 2) | word64((value & W64LIT(0x3333333333333333)) << 2);
1995  value = word64((value & W64LIT(0xF0F0F0F0F0F0F0F0)) >> 4) | word64((value & W64LIT(0x0F0F0F0F0F0F0F0F)) << 4);
1996  return ByteReverse(value);
1997 #endif
1998 }
1999 
2000 /// \brief Reverses bits in a value
2001 /// \param value the value to reverse
2002 /// \details The template overload of BitReverse operates on signed and unsigned values.
2003 /// Internally the size of T is checked, and then value is cast to a byte,
2004 /// word16, word32 or word64. After the cast, the appropriate BitReverse
2005 /// overload is called.
2006 template <class T>
2007 inline T BitReverse(T value)
2008 {
2009  if (sizeof(T) == 1)
2010  return (T)BitReverse((byte)value);
2011  else if (sizeof(T) == 2)
2012  return (T)BitReverse((word16)value);
2013  else if (sizeof(T) == 4)
2014  return (T)BitReverse((word32)value);
2015  else
2016  {
2017  CRYPTOPP_ASSERT(sizeof(T) == 8);
2018  return (T)BitReverse((word64)value);
2019  }
2020 }
2021 
2022 /// \brief Reverses bytes in a value depending upon endianness
2023 /// \tparam T the class or type
2024 /// \param order the ByteOrder of the data
2025 /// \param value the value to conditionally reverse
2026 /// \details Internally, the ConditionalByteReverse calls NativeByteOrderIs.
2027 /// If order matches native byte order, then the original value is returned.
2028 /// If not, then ByteReverse is called on the value before returning to the caller.
2029 template <class T>
2030 inline T ConditionalByteReverse(ByteOrder order, T value)
2031 {
2032  return NativeByteOrderIs(order) ? value : ByteReverse(value);
2033 }
2034 
2035 /// \brief Reverses bytes in an element from an array of elements
2036 /// \tparam T the class or type
2037 /// \param out the output array of elements
2038 /// \param in the input array of elements
2039 /// \param byteCount the total number of bytes in the array
2040 /// \details Internally, ByteReverse visits each element in the in array
2041 /// calls ByteReverse on it, and writes the result to out.
2042 /// \details ByteReverse does not process tail byes, or bytes that are
2043 /// not part of a full element. If T is int (and int is 4 bytes), then
2044 /// <tt>byteCount = 10</tt> means only the first 2 elements or 8 bytes are
2045 /// reversed.
2046 /// \details The follwoing program should help illustrate the behavior.
2047 /// <pre>vector<word32> v1, v2;
2048 ///
2049 /// v1.push_back(1);
2050 /// v1.push_back(2);
2051 /// v1.push_back(3);
2052 /// v1.push_back(4);
2053 ///
2054 /// v2.resize(v1.size());
2055 /// ByteReverse<word32>(&v2[0], &v1[0], 16);
2056 ///
2057 /// cout << "V1: ";
2058 /// for(unsigned int i = 0; i < v1.size(); i++)
2059 /// cout << std::hex << v1[i] << " ";
2060 /// cout << endl;
2061 ///
2062 /// cout << "V2: ";
2063 /// for(unsigned int i = 0; i < v2.size(); i++)
2064 /// cout << std::hex << v2[i] << " ";
2065 /// cout << endl;</pre>
2066 /// The program above results in the follwoing output.
2067 /// <pre>V1: 00000001 00000002 00000003 00000004
2068 /// V2: 01000000 02000000 03000000 04000000</pre>
2069 /// \sa ConditionalByteReverse
2070 template <class T>
2071 void ByteReverse(T *out, const T *in, size_t byteCount)
2072 {
2073  // Alignment check due to Issues 690
2074  CRYPTOPP_ASSERT(byteCount % sizeof(T) == 0);
2075  CRYPTOPP_ASSERT(IsAligned<T>(in));
2076  CRYPTOPP_ASSERT(IsAligned<T>(out));
2077 
2078  size_t count = byteCount/sizeof(T);
2079  for (size_t i=0; i<count; i++)
2080  out[i] = ByteReverse(in[i]);
2081 }
2082 
2083 /// \brief Conditionally reverses bytes in an element from an array of elements
2084 /// \tparam T the class or type
2085 /// \param order the ByteOrder of the data
2086 /// \param out the output array of elements
2087 /// \param in the input array of elements
2088 /// \param byteCount the byte count of the arrays
2089 /// \details Internally, ByteReverse visits each element in the in array
2090 /// calls ByteReverse on it depending on the desired endianness, and writes the result to out.
2091 /// \details ByteReverse does not process tail byes, or bytes that are
2092 /// not part of a full element. If T is int (and int is 4 bytes), then
2093 /// <tt>byteCount = 10</tt> means only the first 2 elements or 8 bytes are
2094 /// reversed.
2095 /// \sa ByteReverse
2096 template <class T>
2097 inline void ConditionalByteReverse(ByteOrder order, T *out, const T *in, size_t byteCount)
2098 {
2099  if (!NativeByteOrderIs(order))
2100  ByteReverse(out, in, byteCount);
2101  else if (in != out)
2102  memcpy_s(out, byteCount, in, byteCount);
2103 }
2104 
2105 template <class T>
2106 inline void GetUserKey(ByteOrder order, T *out, size_t outlen, const byte *in, size_t inlen)
2107 {
2108  const size_t U = sizeof(T);
2109  CRYPTOPP_ASSERT(inlen <= outlen*U);
2110  memcpy_s(out, outlen*U, in, inlen);
2111  memset_z((byte *)out+inlen, 0, outlen*U-inlen);
2112  ConditionalByteReverse(order, out, out, RoundUpToMultipleOf(inlen, U));
2113 }
2114 
2115 inline byte UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const byte *)
2116 {
2117  CRYPTOPP_UNUSED(order);
2118  return block[0];
2119 }
2120 
2121 inline word16 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word16 *)
2122 {
2123  return (order == BIG_ENDIAN_ORDER)
2124  ? block[1] | (block[0] << 8)
2125  : block[0] | (block[1] << 8);
2126 }
2127 
2128 inline word32 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word32 *)
2129 {
2130  return (order == BIG_ENDIAN_ORDER)
2131  ? word32(block[3]) | (word32(block[2]) << 8) | (word32(block[1]) << 16) | (word32(block[0]) << 24)
2132  : word32(block[0]) | (word32(block[1]) << 8) | (word32(block[2]) << 16) | (word32(block[3]) << 24);
2133 }
2134 
2135 inline word64 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word64 *)
2136 {
2137  return (order == BIG_ENDIAN_ORDER)
2138  ?
2139  (word64(block[7]) |
2140  (word64(block[6]) << 8) |
2141  (word64(block[5]) << 16) |
2142  (word64(block[4]) << 24) |
2143  (word64(block[3]) << 32) |
2144  (word64(block[2]) << 40) |
2145  (word64(block[1]) << 48) |
2146  (word64(block[0]) << 56))
2147  :
2148  (word64(block[0]) |
2149  (word64(block[1]) << 8) |
2150  (word64(block[2]) << 16) |
2151  (word64(block[3]) << 24) |
2152  (word64(block[4]) << 32) |
2153  (word64(block[5]) << 40) |
2154  (word64(block[6]) << 48) |
2155  (word64(block[7]) << 56));
2156 }
2157 
2158 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, byte value, const byte *xorBlock)
2159 {
2160  CRYPTOPP_UNUSED(order);
2161  block[0] = static_cast<byte>(xorBlock ? (value ^ xorBlock[0]) : value);
2162 }
2163 
2164 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word16 value, const byte *xorBlock)
2165 {
2166  if (order == BIG_ENDIAN_ORDER)
2167  {
2168  if (xorBlock)
2169  {
2170  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2171  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2172  }
2173  else
2174  {
2175  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2176  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2177  }
2178  }
2179  else
2180  {
2181  if (xorBlock)
2182  {
2183  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2184  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2185  }
2186  else
2187  {
2188  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2189  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2190  }
2191  }
2192 }
2193 
2194 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word32 value, const byte *xorBlock)
2195 {
2196  if (order == BIG_ENDIAN_ORDER)
2197  {
2198  if (xorBlock)
2199  {
2200  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2201  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2202  block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2203  block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2204  }
2205  else
2206  {
2207  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2208  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2209  block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2210  block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2211  }
2212  }
2213  else
2214  {
2215  if (xorBlock)
2216  {
2217  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2218  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2219  block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2220  block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2221  }
2222  else
2223  {
2224  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2225  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2226  block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2227  block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2228  }
2229  }
2230 }
2231 
2232 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word64 value, const byte *xorBlock)
2233 {
2234  if (order == BIG_ENDIAN_ORDER)
2235  {
2236  if (xorBlock)
2237  {
2238  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
2239  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
2240  block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
2241  block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
2242  block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2243  block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2244  block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2245  block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2246  }
2247  else
2248  {
2249  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
2250  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
2251  block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
2252  block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
2253  block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2254  block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2255  block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2256  block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2257  }
2258  }
2259  else
2260  {
2261  if (xorBlock)
2262  {
2263  block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2264  block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2265  block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2266  block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2267  block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
2268  block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
2269  block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
2270  block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
2271  }
2272  else
2273  {
2274  block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
2275  block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
2276  block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
2277  block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
2278  block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
2279  block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
2280  block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
2281  block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
2282  }
2283  }
2284 }
2285 
2286 /// \brief Access a block of memory
2287 /// \tparam T class or type
2288 /// \param assumeAligned flag indicating alignment
2289 /// \param order the ByteOrder of the data
2290 /// \param block the byte buffer to be processed
2291 /// \returns the word in the specified byte order
2292 /// \details GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates
2293 /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
2294 /// LITTLE_ENDIAN_ORDER.
2295 /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w</tt>
2296 /// will be <tt>0x03020100</tt>.
2297 /// <pre>
2298 /// word32 w;
2299 /// byte buffer[4] = {0,1,2,3};
2300 /// w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer);
2301 /// </pre>
2302 template <class T>
2303 inline T GetWord(bool assumeAligned, ByteOrder order, const byte *block)
2304 {
2305  CRYPTOPP_UNUSED(assumeAligned);
2306 
2307  T temp;
2308  memcpy(&temp, block, sizeof(T));
2309  return ConditionalByteReverse(order, temp);
2310 }
2311 
2312 /// \brief Access a block of memory
2313 /// \tparam T class or type
2314 /// \param assumeAligned flag indicating alignment
2315 /// \param order the ByteOrder of the data
2316 /// \param result the word in the specified byte order
2317 /// \param block the byte buffer to be processed
2318 /// \details GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates
2319 /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
2320 /// LITTLE_ENDIAN_ORDER.
2321 /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w</tt>
2322 /// will be <tt>0x03020100</tt>.
2323 /// <pre>
2324 /// word32 w;
2325 /// byte buffer[4] = {0,1,2,3};
2326 /// w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer);
2327 /// </pre>
2328 template <class T>
2329 inline void GetWord(bool assumeAligned, ByteOrder order, T &result, const byte *block)
2330 {
2331  result = GetWord<T>(assumeAligned, order, block);
2332 }
2333 
2334 /// \brief Access a block of memory
2335 /// \tparam T class or type
2336 /// \param assumeAligned flag indicating alignment
2337 /// \param order the ByteOrder of the data
2338 /// \param block the destination byte buffer
2339 /// \param value the word in the specified byte order
2340 /// \param xorBlock an optional byte buffer to xor
2341 /// \details PutWord() provides alternate write access to a block of memory. The flag assumeAligned indicates
2342 /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
2343 /// LITTLE_ENDIAN_ORDER.
2344 template <class T>
2345 inline void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock = NULLPTR)
2346 {
2347  CRYPTOPP_UNUSED(assumeAligned);
2348 
2349  T t1, t2;
2350  t1 = ConditionalByteReverse(order, value);
2351  if (xorBlock) {memcpy(&t2, xorBlock, sizeof(T)); t1 ^= t2;}
2352  memcpy(block, &t1, sizeof(T));
2353 }
2354 
2355 /// \brief Access a block of memory
2356 /// \tparam T class or type
2357 /// \tparam B enumeration indicating endianness
2358 /// \tparam A flag indicating alignment
2359 /// \details GetBlock() provides alternate read access to a block of memory. The enumeration B is
2360 /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
2361 /// Repeatedly applying operator() results in advancing in the block of memory.
2362 /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w1</tt>
2363 /// will be <tt>0x03020100</tt> and <tt>w1</tt> will be <tt>0x07060504</tt>.
2364 /// <pre>
2365 /// word32 w1, w2;
2366 /// byte buffer[8] = {0,1,2,3,4,5,6,7};
2367 /// GetBlock<word32, LittleEndian> block(buffer);
2368 /// block(w1)(w2);
2369 /// </pre>
2370 template <class T, class B, bool A=false>
2372 {
2373 public:
2374  /// \brief Construct a GetBlock
2375  /// \param block the memory block
2376  GetBlock(const void *block)
2377  : m_block((const byte *)block) {}
2378 
2379  /// \brief Access a block of memory
2380  /// \tparam U class or type
2381  /// \param x the value to read
2382  /// \returns pointer to the remainder of the block after reading x
2383  template <class U>
2385  {
2386  CRYPTOPP_COMPILE_ASSERT(sizeof(U) >= sizeof(T));
2387  x = GetWord<T>(A, B::ToEnum(), m_block);
2388  m_block += sizeof(T);
2389  return *this;
2390  }
2391 
2392 private:
2393  const byte *m_block;
2394 };
2395 
2396 /// \brief Access a block of memory
2397 /// \tparam T class or type
2398 /// \tparam B enumeration indicating endianness
2399 /// \tparam A flag indicating alignment
2400 /// \details PutBlock() provides alternate write access to a block of memory. The enumeration B is
2401 /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
2402 /// Repeatedly applying operator() results in advancing in the block of memory.
2403 /// \details An example of writing two word32 values from a block of memory is shown below. After the code
2404 /// executes, the byte buffer will be <tt>{0,1,2,3,4,5,6,7}</tt>.
2405 /// <pre>
2406 /// word32 w1=0x03020100, w2=0x07060504;
2407 /// byte buffer[8];
2408 /// PutBlock<word32, LittleEndian> block(NULLPTR, buffer);
2409 /// block(w1)(w2);
2410 /// </pre>
2411 template <class T, class B, bool A=false>
2413 {
2414 public:
2415  /// \brief Construct a PutBlock
2416  /// \param block the memory block
2417  /// \param xorBlock optional mask
2418  PutBlock(const void *xorBlock, void *block)
2419  : m_xorBlock((const byte *)xorBlock), m_block((byte *)block) {}
2420 
2421  /// \brief Access a block of memory
2422  /// \tparam U class or type
2423  /// \param x the value to write
2424  /// \returns pointer to the remainder of the block after writing x
2425  template <class U>
2427  {
2428  PutWord(A, B::ToEnum(), m_block, (T)x, m_xorBlock);
2429  m_block += sizeof(T);
2430  if (m_xorBlock)
2431  m_xorBlock += sizeof(T);
2432  return *this;
2433  }
2434 
2435 private:
2436  const byte *m_xorBlock;
2437  byte *m_block;
2438 };
2439 
2440 /// \brief Access a block of memory
2441 /// \tparam T class or type
2442 /// \tparam B enumeration indicating endianness
2443 /// \tparam GA flag indicating alignment for the Get operation
2444 /// \tparam PA flag indicating alignment for the Put operation
2445 /// \details GetBlock() provides alternate write access to a block of memory. The enumeration B is
2446 /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
2447 /// \sa GetBlock() and PutBlock().
2448 template <class T, class B, bool GA=false, bool PA=false>
2450 {
2451  // function needed because of C++ grammatical ambiguity between expression-statements and declarations
2452  static inline GetBlock<T, B, GA> Get(const void *block) {return GetBlock<T, B, GA>(block);}
2453  typedef PutBlock<T, B, PA> Put;
2454 };
2455 
2456 /// \brief Convert a word to a string
2457 /// \tparam T class or type
2458 /// \param value the word to convert
2459 /// \param order byte order
2460 /// \returns a string representing the value of the word
2461 template <class T>
2462 std::string WordToString(T value, ByteOrder order = BIG_ENDIAN_ORDER)
2463 {
2464  if (!NativeByteOrderIs(order))
2465  value = ByteReverse(value);
2466 
2467  return std::string((char *)&value, sizeof(value));
2468 }
2469 
2470 /// \brief Convert a string to a word
2471 /// \tparam T class or type
2472 /// \param str the string to convert
2473 /// \param order byte order
2474 /// \returns a word representing the value of the string
2475 template <class T>
2476 T StringToWord(const std::string &str, ByteOrder order = BIG_ENDIAN_ORDER)
2477 {
2478  T value = 0;
2479  memcpy_s(&value, sizeof(value), str.data(), UnsignedMin(str.size(), sizeof(value)));
2480  return NativeByteOrderIs(order) ? value : ByteReverse(value);
2481 }
2482 
2483 // ************** help remove warning on g++ ***************
2484 
2485 /// \brief Safely shift values when undefined behavior could occur
2486 /// \tparam overflow boolean flag indicating if overflow is present
2487 /// \details SafeShifter safely shifts values when undefined behavior could occur under C/C++ rules.
2488 /// The class behaves much like a saturating arithmetic class, clamping values rather than allowing
2489 /// the compiler to remove undefined behavior.
2490 /// \sa SafeShifter<true>, SafeShifter<false>
2491 template <bool overflow> struct SafeShifter;
2492 
2493 /// \brief Shifts a value in the presence of overflow
2494 /// \details the true template parameter indicates overflow would occur.
2495 /// In this case, SafeShifter clamps the value and returns 0.
2496 template<> struct SafeShifter<true>
2497 {
2498  /// \brief Right shifts a value that overflows
2499  /// \tparam T class or type
2500  /// \return 0
2501  /// \details Since <tt>overflow == true</tt>, the value 0 is always returned.
2502  /// \sa SafeLeftShift
2503  template <class T>
2504  static inline T RightShift(T value, unsigned int bits)
2505  {
2506  CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits);
2507  return 0;
2508  }
2509 
2510  /// \brief Left shifts a value that overflows
2511  /// \tparam T class or type
2512  /// \return 0
2513  /// \details Since <tt>overflow == true</tt>, the value 0 is always returned.
2514  /// \sa SafeRightShift
2515  template <class T>
2516  static inline T LeftShift(T value, unsigned int bits)
2517  {
2518  CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits);
2519  return 0;
2520  }
2521 };
2522 
2523 /// \brief Shifts a value in the absence of overflow
2524 /// \details the false template parameter indicates overflow would not occur.
2525 /// In this case, SafeShifter returns the shfted value.
2526 template<> struct SafeShifter<false>
2527 {
2528  /// \brief Right shifts a value that does not overflow
2529  /// \tparam T class or type
2530  /// \return the shifted value
2531  /// \details Since <tt>overflow == false</tt>, the shifted value is returned.
2532  /// \sa SafeLeftShift
2533  template <class T>
2534  static inline T RightShift(T value, unsigned int bits)
2535  {
2536  return value >> bits;
2537  }
2538 
2539  /// \brief Left shifts a value that does not overflow
2540  /// \tparam T class or type
2541  /// \return the shifted value
2542  /// \details Since <tt>overflow == false</tt>, the shifted value is returned.
2543  /// \sa SafeRightShift
2544  template <class T>
2545  static inline T LeftShift(T value, unsigned int bits)
2546  {
2547  return value << bits;
2548  }
2549 };
2550 
2551 /// \brief Safely right shift values when undefined behavior could occur
2552 /// \tparam bits the number of bit positions to shift the value
2553 /// \tparam T class or type
2554 /// \param value the value to right shift
2555 /// \result the shifted value or 0
2556 /// \details SafeRightShift safely shifts the value to the right when undefined behavior
2557 /// could occur under C/C++ rules. SafeRightShift will return the shifted value or 0
2558 /// if undefined behavior would occur.
2559 template <unsigned int bits, class T>
2560 inline T SafeRightShift(T value)
2561 {
2562  return SafeShifter<(bits>=(8*sizeof(T)))>::RightShift(value, bits);
2563 }
2564 
2565 /// \brief Safely left shift values when undefined behavior could occur
2566 /// \tparam bits the number of bit positions to shift the value
2567 /// \tparam T class or type
2568 /// \param value the value to left shift
2569 /// \result the shifted value or 0
2570 /// \details SafeLeftShift safely shifts the value to the left when undefined behavior
2571 /// could occur under C/C++ rules. SafeLeftShift will return the shifted value or 0
2572 /// if undefined behavior would occur.
2573 template <unsigned int bits, class T>
2574 inline T SafeLeftShift(T value)
2575 {
2576  return SafeShifter<(bits>=(8*sizeof(T)))>::LeftShift(value, bits);
2577 }
2578 
2579 /// \brief Finds first element not in a range
2580 /// \tparam InputIt Input iterator type
2581 /// \tparam T class or type
2582 /// \param first iterator to first element
2583 /// \param last iterator to last element
2584 /// \param value the value used as a predicate
2585 /// \returns iterator to the first element in the range that is not value
2586 template<typename InputIt, typename T>
2587 inline InputIt FindIfNot(InputIt first, InputIt last, const T &value) {
2588 #ifdef CRYPTOPP_CXX11_LAMBDA
2589  return std::find_if(first, last, [&value](const T &o) {
2590  return value!=o;
2591  });
2592 #else
2593  return std::find_if(first, last, std::bind2nd(std::not_equal_to<T>(), value));
2594 #endif
2595 }
2596 
2597 // ************** use one buffer for multiple data members ***************
2598 
2599 #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);}
2600 #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);}
2601 #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);}
2602 #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);}
2603 #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);}
2604 #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);}
2605 #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);}
2606 #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);}
2607 #define CRYPTOPP_BLOCKS_END(i) size_t SST() {return SS##i();} void AllocateBlocks() {m_aggregate.New(SST());} AlignedSecByteBlock m_aggregate;
2608 
2609 NAMESPACE_END
2610 
2611 #if (CRYPTOPP_MSC_VERSION)
2612 # pragma warning(pop)
2613 #endif
2614 
2615 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
2616 # pragma GCC diagnostic pop
2617 #endif
2618 
2619 #endif
void SecureWipeBuffer(T *buf, size_t n)
Sets each element of an array to 0.
Definition: misc.h:1218
InputIt FindIfNot(InputIt first, InputIt last, const T &value)
Finds first element not in a range.
Definition: misc.h:2587
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:2560
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:2476
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:1467
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:2345
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:2418
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:2545
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:4746
std::string WordToString(T value, ByteOrder order=BIG_ENDIAN_ORDER)
Convert a word to a string.
Definition: misc.h:2462
T rotlVariable(T x, unsigned int y)
Performs a left rotate.
Definition: misc.h:1516
Access a block of memory.
Definition: misc.h:2449
byte BitReverse(byte value)
Reverses bits in a 8-bit value.
Definition: misc.h:1956
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:2303
void SecureWipeArray(T *buf, size_t n)
Sets each element of an array to 0.
Definition: misc.h:1326
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:1416
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:2030
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:2534
#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:2426
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:2376
T SafeLeftShift(T value)
Safely left shift values when undefined behavior could occur.
Definition: misc.h:2574
static T RightShift(T value, unsigned int bits)
Right shifts a value that overflows.
Definition: misc.h:2504
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:1442
Access a block of memory.
Definition: misc.h:2371
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:2384
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:2491
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:2412
std::string IntToString< Integer >(Integer value, unsigned int base)
Converts an Integer to a string.
Definition: integer.cpp:4680
Crypto++ library namespace.
T rotrVariable(T x, unsigned int y)
Performs a right rotate.
Definition: misc.h:1536
T rotlMod(T x, unsigned int y)
Performs a left rotate.
Definition: misc.h:1553
unsigned int GetByte(ByteOrder order, T value, unsigned int index)
Gets a byte from a value.
Definition: misc.h:1878
T rotrMod(T x, unsigned int y)
Performs a right rotate.
Definition: misc.h:1569
T rotrFixed(T x, unsigned int y)
Performs a right rotate.
Definition: misc.h:1492
Ensures an object is not copyable.
Definition: misc.h:228
byte ByteReverse(byte value)
Reverses bytes in a 8-bit value.
Definition: misc.h:1889
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:2516
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