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